I have an activity in which I am having an edittext in which i am entering something and storing that value in HashMap where the data inserted in edittext is the key and static data is the value. Now I am passing that to DialogFragment but I am not able to access the key in DialogFragment. How to access the key in DialogFragment to access the value associated with that key
Here is the code:
MainActivity.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="grepthorsoft.com.hash.MainActivity">
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
android:id="#+id/tt"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/bt"/>
</RelativeLayout>
MainActivity.java
public class MainActivity extends AppCompatActivity {
HashMap<String, String> d;
EditText et;
String s;
FragmentManager fm;
Button bt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
d = new HashMap<>();
et = findViewById(R.id.tt);
fm = getFragmentManager();
bt = findViewById(R.id.bt);
bt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
s = et.getText().toString();
d.put(s, "2");
MyDialog myDialog = new MyDialog(d);
myDialog.show(fm, "test");
}
});
}
}
MyDialog.xml
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="grepthorsoft.com.hash.MyDialog">
</RelativeLayout>
MyDialog.java
public class MyDialog extends DialogFragment{
Button yes,no;
HashMap<String,String> d;
public MyDialog(){}
public MyDialog( HashMap<String,String> d)
{
this.d=d;
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
View v= inflater.inflate(R.layout.activity_my_dialog,null);
return v;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
}
You can do something like this in your dialog fragment ...
for ( String key : d.keySet() ) {
System.out.println("value" + d.get(key ));
}
d.keySet() fetches all the keys from the hashmap d
You are doing this in wrong way.. you should pass any data to DialogFragment via DialogFragment.setArguments() method. For example:
in MainActivity class ->
MyDialog myDialog = new MyDialog();
Bundle extras = new Bundle();
extras.putSerializable("HashMap",d);
myDialog.setArguments(extras);
myDialog.show(fm, "test");
in myDialog class keep only default constructor and remove your constructor and then add this code to onActivityCreated method
Bundle bundle = this.getArguments();
if(bundle != null) {
d = (HashMap<String, String>) bundle.getSerializable("HashMap");
}
for more information you can check here
You should pass the value in your onclick function using setArguments like this..
MyDialog myDialog = new MyDialog(d);
Bundle bundle = new Bundle();
bundle.putSerializable("hashmap",mMap);
myDialog.setArguments(bundle);
myDialog.show(fm, "test");
And then you will get those value using getArguments in yoyr MyDialog fragment
paste this code in your onCreateView
Bundle bundle = this.getArguments();
if(bundle.getSerializable("hashmap") != null)
mMap = (HashMap<String, String>)bundle.getSerializable("hashmap");
//get your hashmap value
Iterator iterator = mMap.keySet().iterator();
while(iterator.hasNext()) {
String key=(String)iterator.next();
String value=(String)mMap.get(key);
}
hasNext() Returns true if the iteration has more elements.
next() Returns the next element in the iteration.
you can access hashmap declare in activity class into the dialog by making hashmap public in the activity and in dialog fragment class access object like this ((MainActivity)getActivity()).d;
and in dialog fragment, you can iterate map like this
void printMap() {
Iterator it = ((MainActivity)getActivity()).d.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pair = (Map.Entry)it.next();
System.out.println(pair.getKey() + " = " + pair.getValue());
}
}
Related
I am trying to create a DialogFragment as
public class PlaceFragment extends DialogFragment {
public PlaceFragment() {
}
public static PlaceFragment newInstance() {
PlaceFragment placeFragment = new PlaceFragment();
Bundle args = new Bundle();
args.putDouble("Latitude", 12.3456);
placeFragment.setArguments(args);
return placeFragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_place, container, false);
AlertDialog.Builder placePicker = new AlertDialog.Builder(getContext());
placePicker.setView(R.layout.fragment_place)
.setTitle("Enter Latitude and Longitude")
.setPositiveButton("Ok", null);
// return inflater.inflate(R.layout.fragment_place, container);
return v;
}
}
which should be called as:
case R.id.action_geolocate:
FragmentManager fm = getSupportFragmentManager();
PlaceFragment placeFragment = PlaceFragment.newInstance();
placeFragment.show(fm, "");
return true;
But, as you can see, this is not working,as this is obviously showing the layout only, which is inflated. But I am trying to get the dialog with two line of EditText with Ok and Dissmiss button.
If I use a completely manual way, then I am getting the editText, but dont have any idea how to get those value with OkButton, like:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_place, container);
}
You can
Create a class extend DialogFragment
override and implement onCreateDialog to configure how the dialog appears. Here, create a Dialog / AlertDialog, can also populate its layout here.
In some cases, you want to implement onCreateView and handle views/actions there.
Hope this would help.
if I understand right, something like this should work:
public class DialogEnterExit extends DialogFragment {
public interface EnterExitDialogListener {
void onFinishEditDialog(String event, String place, Location location);
}
EnterExitDialogListener mListener;
private static final String TAG = DialogEnterExit.class.getSimpleName();
AppCompatDialog mDialog;
String mPlace;
Location mLocation;
public static DialogEnterExit newInstance(String place, Location location) {
DialogEnterExit f = new DialogEnterExit();
// Supply num input as an argument.
Bundle args = new Bundle();
args.putString("PLACE", place);
args.putParcelable("LOCATION", location);
f.setArguments(args);
return f;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mPlace = getArguments().getString("PLACE");
mLocation = getArguments().getParcelable("LOCATION");
}
#NonNull
#Override
public Dialog onCreateDialog(#Nullable Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater layoutInflater = getActivity().getLayoutInflater();
View view = layoutInflater.inflate(R.layout.layout_enter_exit_dialog,null);
final RadioButton enter = view.findViewById(R.id.radio_enter);
final RadioButton exit = view.findViewById(R.id.radio_exit);
TextView place = view.findViewById(R.id.place_picked);
place.setText(mPlace);
enter.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mListener != null) {
mListener.onFinishEditDialog(getString(R.string.dialog_transition_entered), mPlace,
mLocation);
}
mDialog.dismiss();
}
});
exit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mListener != null) {
mListener.onFinishEditDialog(getString(R.string.dialog_transition_exited), mPlace,
mLocation);
}
mDialog.dismiss();
}
});
builder
.setView(view)
.setTitle(getString(R.string.dialog_title_event))
.setCancelable(true);
mDialog = builder.create();
return mDialog;
}
#Override
public void onAttach(#NonNull Context context) {
super.onAttach(context);
// Verify that the host activity implements the callback interface
try {
// Instantiate the EditNameDialogListener so we can send events to the
host
mListener = (EnterExitDialogListener) context;
} catch (ClassCastException e) {
// The activity doesn't implement the interface, throw exception
throw new ClassCastException(context.toString()
+ " must implement EnterExitDialogListener" );
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
}
and the view in xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="place:"
android:layout_weight="1"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/place_picked"
android:hint="place name"
android:layout_weight="3"/>
</LinearLayout>
<RadioButton
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/radio_enter"
android:text="#string/geofence_transition_entered"/>
<RadioButton
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/radio_exit"
android:text="#string/geofence_transition_exited"/>
</LinearLayout>
</LinearLayout>
and to use:
android.location.Location loc = new android.location.Location("");
loc.setLatitude(location.getLatitude());
loc.setLongitude(location.getLongitude());
DialogEnterExit dialogEnterExit = DialogEnterExit.newInstance(location.getName(), loc);
getSupportFragmentManager().beginTransaction()
.add(dialogEnterExit, "enter exit dialog").commitAllowingStateLoss();
i think you should implement
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
instead of
#Override
public View onCreateView(Bundle savedInstanceState) {
and return a dialog instead of view and i think it would be better if you do not leave the tag string in .show(ft,"") empty
I am sending data from one fragment to another, using interface. This works absolutely fine. Now I am trying to use onSaveInstanceState() to save the value in
a Fragment and retrieving in onCreate(). however i'm getting null in Bundle of onCreate(). P.S. everything works fine when i set the Fragment directly into the activity layout in xml. but when i set the fragment through java code into the activity, the onSaveInstanceState is failing. It is not saving the last known value. Please help. Pasting the code below. You can try it out to know the exact issue.
Fragment_A :
public class Fragment_A extends Fragment implements View.OnClickListener {
Button btnAdd;
int counter = 0;
Communicator comm;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(savedInstanceState != null){
counter = savedInstanceState.getInt("counter", 0);
}
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_a, container, false);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
comm = (Communicator) getActivity();
btnAdd = (Button) getActivity().findViewById(R.id.btnAdd);
btnAdd.setOnClickListener(this);
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("counter", counter);
}
#Override
public void onClick(View v) {
counter++;
comm.sendData(counter);
}
}
interface Communicator{
void sendData(int i);
}
=====
Activity :
public class Activity_InterComm extends Activity implements Communicator{
FragmentManager manager;
FragmentTransaction transaction;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_intercomm);
Fragment_A fragment_1 = new Fragment_A();
Fragment_B fragment_2 = new Fragment_B();
manager = getFragmentManager();
transaction = manager.beginTransaction();
transaction.add(R.id.frag_a, fragment_1, "Frag1");
transaction.add(R.id.frag_b, fragment_2, "Frag2");
transaction.commit();
}
#Override
public void sendData(int i) {
manager = getFragmentManager();
Fragment_B fragment_b = (Fragment_B) manager.findFragmentById(R.id.frag_b);
fragment_b.setData("Button has been clicked " + i + " times");
}
}
=====
Fragment_B :
public class Fragment_B extends Fragment {
TextView txtMessage;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_b, container, false);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
txtMessage = (TextView) getActivity().findViewById(R.id.txtMessage);
}
public void setData(String message){
txtMessage.setText(message);
}
}
activity_intercomm.xml :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<!--<fragment
android:id="#+id/frag_a"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_marginBottom="8dp"
android:layout_weight="1"
android:name="android.learning.com.fragintercomm.Fragment_A"/>
<fragment
android:id="#+id/frag_b"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:name="android.learning.com.fragintercomm.Fragment_B"/>-->
<LinearLayout
android:id="#+id/frag_a"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_marginBottom="8dp"
android:layout_weight="1"
android:background="#color/colorAccent"
android:orientation="vertical"/>
<LinearLayout
android:id="#+id/frag_b"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_marginBottom="8dp"
android:layout_weight="1"
android:background="#color/colorPrimaryDark"
android:orientation="vertical"/>
</LinearLayout>
the soluion I found was using getView() instead of getActivity() while initializing the button in Fragment_A. use btnAdd = (Button) getView().findViewById(R.id.btnAdd); instead of btnAdd = (Button) getActivity().findViewById(R.id.btnAdd);.
However, you can't use getView() in Fragment_B. The Textview freezes and, onSaveInstanceStat() doesn't work. Please suggest a solution.
I need to pass data to a fragment, declared in activity layout before it is rendered:
<fragment android:name="com.app.fragments.MyFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/myFragment" />
I tried to do it in Activity's onCreate but fragment is already rendered at that time.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Here fragment is already rendered
mPosts = (MyFragment)getSupportFragmentManager().findFragmentById(R.id.myFragment);
mPosts.setData(someData);
}
I've seen the way when fragment is created programmatically in activity onCreate and than added to a container. It's not a very bad solution. But... Is there anything simpler?
For XML layout there is one question over here: https://stackoverflow.com/a/23226281/842607
Even they has to say you cannot pass arguments, but you can use callbacks or custom attributes.
Else
Normally, we use Bundle in arguments in this way:
Fragment class
public class ShopProductListingFragment extends Fragment {
private static final String TAG = ShopProductListingFragment.class.getSimpleName();
public static final String KEY_CATEGORY = "category";
public static final String KEY_URL_PARAMS = "url_params";
public static final String KEY_URL = "url";
public static ShopProductListingFragment getInstance(NewCategory category, #NonNull HashMap<String, String> urlParams) {
Bundle bundle = new Bundle();
if (null != category)
bundle.putLong(KEY_CATEGORY, category.getCategory_id());
bundle.putSerializable(KEY_URL_PARAMS, urlParams);
ShopProductListingFragment fragment = new ShopProductListingFragment();
fragment.setArguments(bundle);
return fragment;
}
public static ShopProductListingFragment getInstance(#NonNull String url) {
Bundle bundle = new Bundle();
bundle.putSerializable(KEY_URL, url);
ShopProductListingFragment fragment = new ShopProductListingFragment();
fragment.setArguments(bundle);
return fragment;
}
public ShopProductListingFragment() {
// Required empty public constructor
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
initVals();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_shop_product_listing, container, false);
ButterKnife.bind(this, rootView);
initViews();
return rootView;
}
private void initVals() {
Bundle bundle = getArguments();
if (null == bundle || Bundle.EMPTY == bundle)
throw new NullPointerException("Invalid or null arguments passed to fragment ShopProductListingFragment");
if (bundle.containsKey(KEY_CATEGORY))
categoryId = bundle.getLong(KEY_CATEGORY);
mCategory = StyFi.getInstance().getCategory(categoryId);
if (bundle.containsKey(KEY_URL_PARAMS))
urlParams = (HashMap<String, String>) bundle.getSerializable(KEY_URL_PARAMS);
if (bundle.containsKey(KEY_URL))
urlFilter = bundle.getString(KEY_URL);
}
}
Layout file of Activity
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
This is how it is instantiated in Activity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity);
if (null == savedInstanceState) {
ShopProductListingFragment fragment = ShopProductListingFragment.getInstance(category, getUrlParams(data));
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction().replace(R.id.content_frame, fragment, "SHOP");
fragmentTransaction.commit();
}
}
I am doing a sample project as an excercise and want to display two fragments in the same activity when dealing with tablets(7' and 10').
So what I have so far is this.
As you can see I can display the data of my recyclerview in the left (static) fragment. However the right fragment is empty.
So I have two questions.
1) How to display by default in the right fragment the data of the first row of recyclerview?(ie image and article)
2) How to implement the click listener and update the right fragment?
Here is my code:
MainActivity
public class MainActivity extends AppCompatActivity {
private boolean mTwoPane;
private static final String DETAIL_FRAGMENT_TAG = "DFTAG";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(findViewById(R.id.detailed_match_reports)!=null) {
mTwoPane = true;
if (savedInstanceState == null) {
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.detailed_match_reports, new DetailedActivityFragment(),DETAIL_FRAGMENT_TAG)
.commit();
}else{
mTwoPane = false;
}
}
}
}
layout/activity_main.xml
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/match_reports"
android:name="theo.testing.androidservices.fragments.MainActivityFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp"
tools:context="theo.testing.androidservices.activities.MainActivity"
tools:layout="#android:layout/list_content" />
layout-sw600dp/activity_main
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:baselineAligned="false"
android:divider="?android:attr/dividerHorizontal"
android:orientation="horizontal"
tools:context="theo.testing.androidservices.activities.MainActivity">
<fragment
android:id="#+id/match_reports"
android:name="theo.testing.androidservices.fragments.MainActivityFragment"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"
tools:layout="#android:layout/list_content" />
<FrameLayout
android:id="#+id/detailed_match_reports"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="4" />
</LinearLayout>
MainActivityFragment
public class MainActivityFragment extends Fragment {
public static final String TAG = "AelApp";
public static ArrayList<MyModel> listItemsList;
RecyclerView myList;
public static MatchReportsAdapter adapter;
public MainActivityFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
updateMatchReport();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
getActivity().setTitle("Match Report");
View rootView = inflater.inflate(R.layout.fragment_main_activity, container, false);
listItemsList = new ArrayList<>();
myList = (RecyclerView)rootView.findViewById(R.id.listview_match_reports);
final LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
myList.setHasFixedSize(true);
myList.setLayoutManager(linearLayoutManager);
adapter = new MatchReportsAdapter(getActivity(), listItemsList);
myList.setAdapter(adapter);
return rootView;
}
public void updateMatchReport(){
Intent i = new Intent(getActivity(), MatchReport.class);
getActivity().startService(i);
}
}
First let me answer the second question. To show a fragment on the right side of the screen add something like this (note how I'm using that id of the frame layout to replace the fragment):
Fragment fragment = new MyRightSideFragment();
FragmentManager fm = getFragmentManager();
fm.beginTransaction().replace(R.id.detailed_match_reports, fragment).commit();
Now, for the first question, you need to implement click listener, you can find an example here.
public class ReactiveAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
#Override
public void onBindViewHolder(final ViewHolder holder, int position) {
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int position = (Integer)v.getTag();
showDetail(position);
}
});
}
}
Notice that I'm using the tag of the view to identify the position (so somwhere in your onBindViewHolder code you must set this tag).
public function showDetail(int position) {
... show fragment por position
}
and finally, when your in your OnCreateView or somewhere in your setup code, call showDetail(0).
I have a fragment that executes or display a dialog fragment once a button is clicked. This dialog fragment displays a table generated by code, however when I try to click the button on this is displayed
And when I trace it in the LogCat the dialog fragments onCreateView is not called. Can somebody help or explain this to me?. Im not that good in android programming yet and I know i still have a lot to learn.
Here is the code of the fragment that calls the dialog fragment
public class fragment_schedule extends Fragment {
...............
public fragment_schedule(ArrayList<SubjSchedule> subj){
subject = subj;
}
#SuppressWarnings("deprecation")
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
..................
showlstbtn = (Button) rootView.findViewById(R.id.button_showlstschd);
showlstbtn.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
FragmentTransaction ft = getActivity().getFragmentManager().beginTransaction();
ft.addToBackStack(null);
DialogFragment dialog = ShowLstDialog.newInstance(subject);
dialog.show(ft, "dialog");
}
});
..........
and heres my dialog fragment
public class ShowLstDialog extends DialogFragment {
private static final String TAG = ShowLstDialog.class.getSimpleName();
public static Context mContext;
public static TableLayout tl;
public static TableRow trh;
private static ArrayList<SubjSchedule> subject= new ArrayList<SubjSchedule>();
public static DialogFragment newInstance(ArrayList<SubjSchedule> subj) {
// TODO Auto-generated method stub
DialogFragment f = new DialogFragment();
subject = subj;
Log.v(TAG, subject.size()+"");
return f;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Log.v(TAG, "OnCreateView: " + subject.size()+"");
View rootView = inflater.inflate(R.layout.fragment_dialog_showlst, container);
//mEditText = (EditText) view.findViewById(R.id.txt_your_name);
Log.v(TAG, "OnCreateView: " + subject.size()+"");
getDialog().setTitle("");
tl = (TableLayout) rootView.findViewById(R.id.tablelayout_schedlst);
trh = new TableRow(getActivity());
TextView[] tvh = new TextView[3];
for(int i=0; i<3; i++){
tvh[i] = new TextView(getActivity());
tvh[i].setBackgroundResource(R.drawable.green2);
tvh[i].setTextColor(getResources().getColor(R.color.LightCyan));
tvh[i].setGravity(Gravity.CENTER);
tvh[i].setPadding(30, 3, 30, 3);
//tvh[i].setLayoutParams(params);
trh.addView(tvh[i]);
}
tvh[0].setText("Subject");
tvh[1].setText("Description");
tvh[2].setText("Instructor");
TableRow[] tr = new TableRow[subject.size()];
for(int i=0; i<subject.size();i++){
tr[i] = new TableRow(getActivity());
TextView[] tv1 = new TextView[3];
for(int k=0; k<3; k++){
tv1[k] = new TextView(getActivity());
tv1[k].setBackgroundResource(R.drawable.btn_default_disabled_holo_dark);
tv1[k].setTextColor(getResources().getColor(R.color.list_background_pressed));
tv1[k].setGravity(Gravity.CENTER);
tv1[k].setPadding(30, 3, 30, 3);
//tvh[i].setLayoutParams(params);
tr[i].addView(tv1[i]);
}
tv1[0].setText(subject.get(i).getcn());
tv1[1].setText(subject.get(i).getd());
tv1[2].setText(subject.get(i).geti());
tl.addView(tr[i]);
}
return rootView;
}
}
and here is the xml file of the dialog fragment
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical" >
<ScrollView
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:background="#color/LightCyan"
android:scrollbars="vertical" >
<HorizontalScrollView
android:id="#+id/horizontalScrollView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:orientation="horizontal" >
<TableLayout
android:id="#+id/tablelayout_schedlst"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:stretchColumns="*" >
</TableLayout>
</RelativeLayout>
</HorizontalScrollView>
</ScrollView>
</RelativeLayout>
thank you so much in advance.
Change this
public static DialogFragment newInstance(ArrayList<SubjSchedule> subj) {
// TODO Auto-generated method stub
DialogFragment f = new DialogFragment();
subject = subj;
Log.v(TAG, subject.size()+"");
return f;
}
to
public static ShowLstDialog newInstance(ArrayList<SubjSchedule> subj) {
// TODO Auto-generated method stub
ShowLstDialog f = new ShowLstDialog();
subject = subj;
Log.v(TAG, subject.size()+"");
return f;
}
And do read
http://developer.android.com/reference/android/app/DialogFragment.html
Instead of (or in addition to) implementing onCreateView(LayoutInflater, ViewGroup, Bundle) to generate the view hierarchy inside of a dialog, you may implement onCreateDialog(Bundle) to create your own custom Dialog object
So you should use:
#Override
public Dialog onCreateDialog(Bundle savedInstanceState)
to replace:
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
Instead of
public static DialogFragment newInstance(...) {
DialogFragment f = new DialogFragment();
return f;
}
write
public static DialogFragment newInstance(...) {
DialogFragment f = new ShowLstDialog();
return f;
}
and also use Bundle and setArguments, getArguments to pass arguments.