I am pretty new in android programming. What I have is an app with some tabs, each associate with some fragments. I want to change the layout of the fragment. But I don't want to mess up with the tabs. I am trying to achieve this from a class that extends AsyncTask's onPostExecute() method. I tried to inflate the layout, but it also affects the tabs. I just want to change the fragment only. Here is the code so far:
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
lInflater = inflater;
mContainer = container;
final View rootView = inflater.inflate(R.layout.symptoms_layout, container, false);
textList = new ArrayList();
final LinearLayout mLinearLayout = (LinearLayout) rootView.findViewById(R.id.ll);
Button mButton = (Button) mLinearLayout.findViewById(R.id.btn_add);
Button test = (Button) mLinearLayout.findViewById(R.id.btn_search_sym);
cAdapter = new CustomArrayAdapter(textList,getActivity().getApplicationContext(),test);
ListView lView = (ListView)mLinearLayout.findViewById(R.id.list_symptoms);
lView.setAdapter(cAdapter);
test.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
try {
Log.d("SymFrag",String.valueOf(cAdapter.getCount()));
String[] list = new String[cAdapter.getCount()];
StringBuilder sb = new StringBuilder();
for (int i = 0; i < cAdapter.getCount(); i++) {
Log.d("SymFrag", "Im in for loop");
String temp = cAdapter.getItem(i).toString();
sb.append(temp);
sb.append(",");
}
/*new BackgroundManager(new BackgroundManager.AsyncResponse() {
#Override
public void processFinish(String output) {
String[] out = output.split(",");
for(int i = 0; i < out.length; i++){
Log.d("ProFin",out[i]);
}
}
}).execute(sb.toString());*/
new BackgroundManager(getActivity(),lInflater,mContainer).execute(sb.toString());
} catch (Exception e) {
Log.e("SymFag",e.toString());
}
}
});
mButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
/*LayoutInflater layoutInflater = (LayoutInflater)
getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mLinearLayout.addView(layoutInflater.inflate(R.layout.new_added,null));
TextView tv = (TextView)rootView.findViewById(R.id.symtex);
TextView t = (TextView)mLinearLayout.findViewWithTag("tex");
textList.add(tv.getText().toString());
t.setText(tv.getText());*/
Button bSearch = (Button) mLinearLayout.findViewById(R.id.btn_search_sym);
TextView tv = (TextView) rootView.findViewById(R.id.symtex);
textList.add(tv.getText().toString());
bSearch.setVisibility(View.VISIBLE);
cAdapter.notifyDataSetChanged();
}
});
return rootView;
}
Above is the fragment I want to update/change.
Thanks in advance.
Related
I'm trying to save the data of 4 variables on the SharedPreferences and load it to a list. My problem is that it shows all the data in the first line of the list. I wanted to split like: Everytime I click the save button I wanted to save the 4 variables and when I click it again and I want to save the new variables and display it a new line.
Showing All on the same index:
TubeDataFragment (save):
public class TubeDataFragment extends Fragment {
List<String> tubeData = new ArrayList<>();
public TubeDataFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_tube_data, container, false);
final Spinner spinnerMaterial = (Spinner) view.findViewById(R.id.snipperMaterial);
ArrayAdapter<String> myAdapter = new ArrayAdapter<String>(getActivity(), R.layout.spinner_item, getResources().getStringArray(R.array.material));
myAdapter.setDropDownViewResource(R.layout.spinner_dropdown_item);
spinnerMaterial.setAdapter(myAdapter);
//controls
Button btn_saveTube = (Button) view.findViewById(R.id.btn_save_tube);
final EditText et_diameter = (EditText) view.findViewById(R.id.et_diameter);
final EditText et_clr = (EditText) view.findViewById(R.id.et_clr);
final EditText et_thickness = (EditText) view.findViewById(R.id.et_thickness);
//guarda dados do tubo
btn_saveTube.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
tubeData.add(" Diameter: " + et_diameter.getText().toString());
tubeData.add(" Thickness: " + et_thickness.getText().toString());
tubeData.add(" CLR: " + et_clr.getText().toString());
tubeData.add(" Material: " + spinnerMaterial.getSelectedItem().toString());
StringBuilder stringBuilder = new StringBuilder();
int i = 1;
for(String data : tubeData)
{
stringBuilder.append(data);
stringBuilder.append(";");
if(i++ == tubeData.size())
{
stringBuilder.append("\n");
}
}
SharedPreferences settings = getActivity().getSharedPreferences("PREFS",0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("tubeData", stringBuilder.toString());
editor.commit();
}
});
return view;
}
}
ArchiveFragment (load)
public class ArchiveFragment extends Fragment {
public ArchiveFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_archive, container, false);
ListView tubeDataList = (ListView) view.findViewById(R.id.tubeData_list);
//load tube data
SharedPreferences settings = getActivity().getSharedPreferences("PREFS",0);
String tubeDataString = settings.getString("tubeData", "");
String[] tubeDataSplit = tubeDataString.split("\n");
List<String> tubeDataItems = new ArrayList<>();
for(int i=0; i<tubeDataSplit.length;i++)
{
tubeDataItems.add(tubeDataSplit[i]);
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, android.R.id.text1, tubeDataItems);
// Assign adapter to ListView
tubeDataList.setAdapter(adapter);
return view;
}
}
Your if condition is wrong.
In TubeDataFragment, use below codes in onClick() method:
.............
..................
StringBuilder stringBuilder = new StringBuilder();
int i = 1;
for(String data : tubeData)
{
stringBuilder.append(data);
stringBuilder.append(";");
if(i == 4)
{
stringBuilder.append("\n");
i = 0;
}
i++;
}
...............
.......................
Hey I'm new to fragments in android. I have 3 fragments and this is second one. I want to have data set to its list view from the api by json. Im using Volley library.
But When i run this nothing is set on text view and logs show that requestqueue is running but its not showing up. I used the same thing in normal activity and its working there but not here.
Please help me out with this.
TwoFragment .java
public class TwoFragment extends Fragment {
RequestQueue requestQueue;
String url = "apiUrl";
ArrayList<HistoryEx> histories;
HistoryAdapterEx historyAdapter;
ListView lv;
TextView tv;
public TwoFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_two, null);
histories = new ArrayList<>();
historyAdapter = new HistoryAdapterEx(getActivity(),histories);
lv = (ListView) getView().findViewById(R.id.recentex);
lv.setAdapter(historyAdapter);
getRecent();
return v;
}
void getRecent() {
requestQueue = Volley.newRequestQueue(this.getActivity());
JsonObjectRequest jor = new JsonObjectRequest(url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray ja = response.getJSONArray("entries");
for (int i = 0; i < ja.length(); i++) {
JSONObject jb = ja.getJSONObject(i);
String extype = jb.getString("type");
String exname = jb.getString("name");
HistoryEx history = new HistoryEx();
history.setExname(exname);
history.setExtype(extype);
histories.add(history);
tv.setText(exname);
}
//while ends to get object
} catch (JSONException e) {
e.printStackTrace();
}
}//onresponse
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity(), "Error in loading history.", Toast.LENGTH_LONG).show();
Log.e("Volley", error.toString());
}
}
) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<>();
headers.put("Authorization", "jjhj");
return headers;
}
};
requestQueue.add(jor);
/*
end of Json parsing
*/
}
}
HistoryAdapterEx.java
public class HistoryAdapterEx extends BaseAdapter {
ArrayList<HistoryEx> histories;
LayoutInflater inflater;
Activity activity;
public HistoryAdapterEx(Activity activity, ArrayList groups){
super();
this.histories =new ArrayList<>();
this.activity=activity;
this.histories =groups;
}
public int getCount() {
return histories.size();
}
public Object getItem(int i) {
return histories.get(i);
}
public long getItemId(int i) {
return 0;
}
public View getView(int i, View view, ViewGroup viewGroup) {
if (inflater == null)
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (view == null)
view = inflater.inflate(R.layout.list_item_ex1, null);
TextView name = (TextView) view.findViewById(R.id.exercise);
TextView ac1 = (TextView) view.findViewById(R.id.Achieved1);
TextView ac2 = (TextView) view.findViewById(R.id.Achieved2);
TextView ac3 = (TextView) view.findViewById(R.id.Achieved3);
TextView ta1 = (TextView) view.findViewById(R.id.target1);
TextView ta2 = (TextView) view.findViewById(R.id.target2);
TextView ta3= (TextView) view.findViewById(R.id.target3);
HistoryEx history = histories.get(i);
System.out.println("ex.. "+history);
name.setText(history.getExname());
ac1.setText(history.getExname());
ac2.setText(history.getExname());
ac3.setText(history.getExname());
ta1.setText(history.getExtype());
ta2.setText(history.getExtype());
ta3.setText(history.getExtype());
//interests.setText(history.getDescription());
//description.setText(history.getInterests());
return view;
}
}
you have not set reference to TextView check below
Try below code,
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_two, null);
histories = new ArrayList<>();
historyAdapter = new HistoryAdapterEx(getActivity(),histories);
tv = (TextView) v.findViewById(R.id.YOURTEXTVIEWID);
lv = (ListView) v.findViewById(R.id.recentex);
lv.setAdapter(historyAdapter);
getRecent();
return v;
}
Also Change Your Response Code as below
#Override
public void onResponse(JSONObject response) {
try {
JSONArray ja = response.getJSONArray("entries");
for (int i = 0; i < ja.length(); i++) {
JSONObject jb = ja.getJSONObject(i);
String extype = jb.getString("type");
String exname = jb.getString("name");
HistoryEx history = new HistoryEx();
history.setExname(exname);
history.setExtype(extype);
histories.add(history);
tv.setText(exname);
}
historyAdapter.notifyDatasetChanged();
//while ends to get object
} catch (JSONException e) {
e.printStackTrace();
}
}//onresponse
Its a very little mistake I Guess
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_two, null);
histories = new ArrayList<>();
historyAdapter = new HistoryAdapterEx(getActivity(),histories);
lv = (ListView) getView().findViewById(R.id.recentex);
lv.setAdapter(historyAdapter);
getRecent();
return v;
}
replace above code with below snippet
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_two, null);
histories = new ArrayList<>();
getRecent();
historyAdapter = new HistoryAdapterEx(getActivity(),histories);
lv = (ListView) getView().findViewById(R.id.recentex);
lv.setAdapter(historyAdapter);
return v;
}
It will be filled after getRecent(); then call it before initialize adapter
histories = new ArrayList<>();
lv = (ListView) getView().findViewById(R.id.recentex);
getRecent();
set it here is proper way ..
for (int i = 0; i < ja.length(); i++) {
....
}
historyAdapter = new HistoryAdapterEx(getActivity(),histories);
lv.setAdapter(historyAdapter);
This question already has answers here:
How do I pass data between Activities in Android application?
(53 answers)
Closed 6 years ago.
I want to call the function populateTimeList() in MainFragmentActivity2 class from the onClick function of TimePickerPopup class. How do I do so? these are the codes respectively. I am very new to android, please help!
public class MainActivityFragment2 extends Fragment {
private List<TimeList> TDList = new ArrayList<TimeList>();
public MainActivityFragment2() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
private void populateTimeList() {
Context ctx = this.getActivity();
DBoperations db = new DBoperations(ctx);
Cursor cr = db.getInformation(db);
cr.moveToFirst();
String TimeH, TimeM, EtimeH, EtimeM;
do {
TimeH = Integer.toString(cr.getInt(1));
TimeM = Integer.toString(cr.getInt(2));
EtimeH = Integer.toString(cr.getInt(3));
EtimeM = Integer.toString(cr.getInt(4));
TDList.add((new TimeList(TimeH + " : " + TimeM, EtimeH + " : " + EtimeM)));
}while (cr.moveToNext());
}
private class MyAdapter extends ArrayAdapter<TimeList> {
public MyAdapter(Context context, List<TimeList> values) {
super(context, R.layout.time_list_item,values);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
LayoutInflater inflater = LayoutInflater.from(getContext());
if( v == null){
v = inflater.inflate(R.layout.time_list_item, parent, false);
}
TimeList currLoc = TDList.get(position);
TextView theTextView = (TextView) v.findViewById(R.id.time_list_item_textview1);
theTextView.setText(currLoc.getTime());
theTextView = (TextView) v.findViewById(R.id.time_list_item_textview2);
theTextView.setText(currLoc.getDuration());
return v;
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.time_list_view, container, false);
ListView list = (ListView) rootView.findViewById(R.id.time_list_view);
final ArrayAdapter<TimeList> adapter = new MyAdapter(getActivity(),TDList);
list.setAdapter(adapter);
populateTimeList();
setRetainInstance(true);
ImageButton ib = (ImageButton) rootView.findViewById(R.id.imageButton1);
ib.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(MainActivityFragment2.this.getActivity(), TimePickerPopup.class));
}
});
return rootView;
}
}
And
public class TimePickerPopup extends Activity {
private List<TimeList> TDList = new ArrayList<TimeList>();
Context ctx =this;
private TimePicker time_picker1;
private TimePicker time_picker2;
private ImageButton select_time1;
private ImageButton select_time2;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.time_picker);
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
int width = dm.widthPixels;
int height = dm.heightPixels;
getWindow().setLayout((int) (width * .8), (int) (height * .7+50));
time_picker1 = (TimePicker) findViewById(R.id.timePicker1);
time_picker2 = (TimePicker) findViewById(R.id.timePicker2);
select_time1 = (ImageButton) findViewById(R.id.selectButton1);
select_time2 = (ImageButton) findViewById(R.id.selectButton2);
select_time1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getBaseContext(), "Start time " + time_picker1.getCurrentHour() + " : " + time_picker1.getCurrentMinute(), Toast.LENGTH_SHORT).show();
ScrollView sv1 = (ScrollView) findViewById(R.id.sv);
sv1.fullScroll(View.FOCUS_DOWN);
}
});
select_time2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getBaseContext(),"End time " + time_picker2.getCurrentHour() + " : " + time_picker2.getCurrentMinute(), Toast.LENGTH_SHORT).show();
DBoperations db = new DBoperations(ctx);
db.putInfo(db, time_picker1.getCurrentHour(), time_picker1.getCurrentMinute(), time_picker2.getCurrentHour(), time_picker2.getCurrentMinute(), 0, 0);
finish();
}
});
}
}
Basically, I want the data just entered in the database from the TimePickerPopup class to show up in the ListView (i.e. refresh my list view). Presently it shows the new entered data after I close and then start my app.
In your xml file inside <fragment> tag add this.
android:tag="any_tag"
To get current object of a Fragment do this in java file (add this in your TimePickerPopup.java's onClick(View v) method)
MainActivityFragment2 ma2 = (MainActivityFragment2) getFragmentManager().findFragmentByTag("any_tag");
ma2.populateTimeList();
I'm using a view pager with a sliding panel inside, so when my panel is expanded it creates a request of users and instantiates viewholders to show them in the list view, the problem is that they get instantiated on wherever they want, how I can tell in what fragment it should be instantiated.
Here is my code:
#Override
public void onPanelAnchored(View panel) {
final View cView = panel;
EndpointInterface Service = ServiceAuthGenerator.createService(EndpointInterface.class);
currentID = sharedpreferences.getInt("CURRENTID", 0);
Call<List<Ride>> call = Service.getPassengers(currentRide);
call.enqueue(new Callback<List<Ride>>() {
#Override
public void onResponse(Response<List<Ride>> response, Retrofit retrofit) {
if (response.isSuccess() && !response.body().isEmpty()) {
dialogx.dismiss();
ArrayList<String> myUsersName = new ArrayList<>();
ArrayList<String> myUsersLastName = new ArrayList<>();
ArrayList<String> myUsersMapDirection = new ArrayList<>();
ArrayList<Integer> myUsersID = new ArrayList<>();
ArrayList<Boolean> myUsersRole = new ArrayList<>();
for (int i = 0; i < response.body().size(); i++) {
myUsersRole.add(response.body().get(i).getRole());
myUsersName.add(response.body().get(i).getUser().getFirst_name());
myUsersLastName.add(response.body().get(i).getUser().getLast_name());
myUsersMapDirection.add(getAdress(new LatLng(response.body().get(i).getOrigin_lat(), response.body().get(i).getOrigin_lng())));
myUsersID.add(response.body().get(i).getId());
currentName = myUsersName.get(i) + " " + myUsersLastName.get(i);
mMap.addMarker(new MarkerOptions().snippet(getAdress(new LatLng(response.body().get(Integer.valueOf(i)).getOrigin_lat(), response.body().get(Integer.valueOf(i)).getOrigin_lng()))).position(new LatLng(response.body().get(Integer.valueOf(i)).getOrigin_lat(), response.body().get(Integer.valueOf(i)).getOrigin_lng())).title(response.body().get(Integer.valueOf(i)).getUser().getFirst_name()).icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA)));
}
ListAdapter userAdapter = new CustomAdapterRequest(MainMenu.this, myUsersName, myUsersLastName, myUsersMapDirection, myUsersID, myUsersRole, currentRide);
ListView userListView = (ListView) cView.findViewById(R.id.listViewUserRequest);
userListView.setAdapter(userAdapter);
}
}
#Override
public void onFailure(Throwable t) {
Toast.makeText(getApplicationContext(), "no", Toast.LENGTH_SHORT).show();
}
});
}
Also, here is my adapter code:
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View row = convertView;
myViewHolder holder = null;
if (row == null) {
LayoutInflater customInflater = (LayoutInflater) contexto.getSystemService(contexto.LAYOUT_INFLATER_SERVICE);
row = customInflater.inflate(R.layout.custom_row_request, parent, false);
holder = new myViewHolder(row);
row.setTag(holder);
} else {
holder = (myViewHolder) row.getTag();
}
String singleNameItem = itemName.get(position);
String singleLastNameItem = itemLastName.get(position);
String singleDir = itemDirection.get(position);
Integer singleID = itemIDs.get(position);
Boolean singleRole = itemRoles.get(position);
holder.tv_name.setText(singleNameItem + " " + singleLastNameItem);
holder.tv_Direction.setText(singleDir);
holder.im_profilepic.setImageResource(R.mipmap.profile_photo3);
return row;
}
And my holder class.
class myViewHolder {
TextView tv_name;
TextView tv_Direction;
ImageView im_profilepic;
myViewHolder(View v) {
tv_name = (TextView) v.findViewById(R.id.nameText);
tv_Direction = (TextView) v.findViewById(R.id.originText);
im_profilepic = (ImageView) v.findViewById(R.id.ivImage);
}
}
This is the Fragment class
public class fragment1 extends Fragment {
public fragment1() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
if (container == null) {
return null;
}
return (CardView) inflater.inflate(R.layout.layout1, container, false);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
public void setTextDestination(String origin, String Destination, Long Date, String estimatedTime, boolean singleRole) {
TextView tv_Destination = (TextView) getView().findViewById(R.id.TextDestination);
TextView tv_origin = (TextView) getView().findViewById(R.id.TextOrigin);
TextView tv_Date = (TextView) getView().findViewById(R.id.textDatePager);
TextView tv_EstimatedTiem = (TextView) getView().findViewById(R.id.estimatedTimeRoute);
ImageView iv_roleType = (ImageView) getView().findViewById(R.id.ImgView_roleTypeLayout1);
tv_Destination.setText(Destination);
tv_origin.setText(origin);
iv_roleType.setImageResource(singleRole ? R.mipmap.steerorange3 : R.mipmap.handorange3);
tv_EstimatedTiem.setText(estimatedTime);
java.util.Date date = new Date(Date * 1000L);
DateFormat format = new SimpleDateFormat("dd-MM-yyyy hh:mm a");
format.setTimeZone(TimeZone.getDefault());
String formatted = format.format(date);
tv_Date.setText(formatted);
}
}
I created a list of fragment1 which is mu fragment class and added it to a list, then depending on how many items on the list I have is the number of instances I get, my set text function works correctly but I don't know how to do that with the list view!
Thanks! :D
moved the method that added the list view to the fragment that was instantiated.
I am working in a fragment. When the fragment is called it inflates a layout. Which all works.
v = createTreeView( inflater, container, savedInstanceState);
On my action bar I have a search button which Onclicks changes the layout
btnSearch.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0) {
v = createFliterLivstView( linflate, VContainer);
count = 1;
Log.i("Create","creating tree view kind of ");
}
});
Both views work separately, but when I move the createFilterListView to the OnClick functions it does nothing. The Log has been processed which means it is running through. It just is not inflating the layout.
Below is the onCreateView
#Override
public View onCreateView( LayoutInflater inflater, ViewGroup container, final Bundle savedInstanceState) {
linflate = inflater;
VContainer = container;
m_Context = inflater.getContext();
thisApp = (ThisApp)getActivity().getApplicationContext();
v = createTreeView( inflater, container, savedInstanceState);
FragmentActivity actionBar = getActivity();
View d = actionBar.getActionBar().getCustomView().findViewById(R.id.btn_search);
ImageButton btnSearch = (ImageButton)d.findViewById(R.id.btn_search);
btnSearch.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0) {
v = createFliterLivstView( linflate, VContainer);
count = 1;
Log.i("Create","creating tree view kind of ");
}
});
View b = actionBar.getActionBar().getCustomView().findViewById(R.id.btn_cancel_search);
ImageButton btnCancelSearch = (ImageButton)b.findViewById(R.id.btn_cancel_search);
btnCancelSearch.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0) {
v = createTreeView( linflate, VContainer, savedInstanceState);
}
});
return v;
}
Any help would be greatly appreciated. Thank you in advance.
private View createFliterLivstView( LayoutInflater inflater, ViewGroup container){
View v1 = linflate.inflate(R.layout.list_main, VContainer, false);
historyContainer = (FrameLayout)v1.findViewById(R.id.history_container_layout);
FragmentActivity actionBar = getActivity();
View d = actionBar.getActionBar().getCustomView().findViewById(R.id.txtSearch);
EditText filterEditText = (EditText)d.findViewById(R.id.txtSearch);
filterEditText.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
Log.i("anish", s.toString());
historyContainer.removeAllViews();
final List<String> tempHistoryList = new ArrayList<String>();
tempHistoryList.addAll(historyList);
for(String data : historyList) {
if(data.indexOf(s.toString()) == -1) {
tempHistoryList.remove(data);
}
}
viewStub = new ViewStub(getActivity().getBaseContext(), R.layout.history_schedule);
viewStub.setOnInflateListener(new ViewStub.OnInflateListener() {
#Override
public void onInflate(ViewStub stub, View inflated) {
setUIElements(inflated, tempHistoryList);
}
});
historyContainer.addView(viewStub);
viewStub.inflate();
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
});
setViewStub();
return v1;
}
Below is the CreateTreeView
private View createTreeView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View v = inflater.inflate(R.layout.layout_list_symptoms, container, false);
makeList();
Button btnNext = (Button)v.findViewById(R.id.btn_next);
btnNext.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0) {
String bsafe = thisApp.app_pref.getString("BSAFE", "0");
if(bsafe==null || bsafe.equalsIgnoreCase("0")) {
thisApp.app_edit.putString("SYMTOMS", "");
thisApp.app_edit.commit();
}
Set<Long> sel = fancyAdapter.selected;
Iterator<Long> it = sel.iterator();
boolean hasDone = false;
int i = 0;
while(it.hasNext()) {
Long longId = it.next();
//Log.i(TAG, "...id = " + longId);
final Integer[] hierarchy = fancyAdapter.getManager().getHierarchyDescription(longId);
// 5678
WorkVO vo = list.get(longId.intValue());
try {
pnObj.put("value" , jsonArr.put(vo.getName()) );
//i++;
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
hasDone = true;
}
jsonSymptoms.put(pnObj);
Log.i("Symtoms ", " json="+ jsonSymptoms.toString());
thisApp.app_edit.putString("SYMTOMS", jsonSymptoms.toString());
thisApp.app_edit.commit();
if(hasDone) {
if(bsafe!=null && bsafe.equalsIgnoreCase("1")) {
mCallback.onNextWork(DefinedConstants.FRAG_BSAFE_REPORT);
} else {
mCallback.onNextWork(DefinedConstants.FRAG_FATIGUE_RATING);
}
} else {
Toast.makeText(getActivity(), "Please make a selection", 0).show();
}
}
});
TreeType newTreeType = null;
boolean newCollapsible;
if (savedInstanceState == null) {
manager = new InMemoryTreeStateManager<Long>();
final TreeBuilder<Long> treeBuilder = new TreeBuilder<Long>(manager);
for (int i = 0; i < NODES.length; i++) {
treeBuilder.sequentiallyAddNextNode((long) i, NODES[i]);
}
//Log.d(TAG, manager.toString());
newTreeType = TreeType.FANCY;
newCollapsible = true;
} else {
manager = (TreeStateManager<Long>) savedInstanceState
.getSerializable("treeManager");
if (manager == null) {
manager = new InMemoryTreeStateManager<Long>();
}
newTreeType = (TreeType) savedInstanceState
.getSerializable("treeType");
if (newTreeType == null) {
newTreeType = TreeType.SIMPLE;
}
newCollapsible = savedInstanceState.getBoolean("collapsible");
}
treeView = (TreeViewList) v.findViewById(R.id.mainTreeView);
fancyAdapter = new FancyColouredVariousSizesAdapter(getActivity(), selected,
manager, LEVEL_NUMBER, job_kind, list);
simpleAdapter = new SimpleStandardAdapter(getActivity(), selected, manager,
LEVEL_NUMBER, job_kind, list);
setTreeAdapter(newTreeType);
setCollapsible(newCollapsible);
registerForContextMenu(treeView);
manager.collapseChildren(null);
return v;
}
Inflate a view with this method.
View v = View.inflate(m_context,R.layout.yourlayout,null);
The createView method returns a View which sets the view for the fragment. What you are doing in the onClick is creating a view that isn't overriding your fragments main view.
To be honest it would be much easier and would require less state logic if on click you replaced the Fragment with a new Fragment with the layout you wanted.
Having a Fragment that handles two separate layouts is harder to maintain and to keep the correct state. Not to mention will make the class much larger.