ListView declared in layout is null in onCreateView - android

I'm trying to create a DialogFragment with a ListView and some Buttons. I'm declaring all of them i the layout file and the buttons are working fine but the ListView is null when i use fineViewByID().
Here's my xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/category_picker"
android:layout_gravity="center"
android:orientation="vertical" >
<ListView
android:id="#+id/lvCategorys"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_weight="0.5" >
</ListView>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="100dp"
android:layout_gravity="bottom"
android:layout_weight="0.5"
android:orientation="horizontal" >
<Button
android:id="#+id/btnAddNew"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="0.5"
android:text="#string/cpf_btnAddNew" />
<Button
android:id="#+id/btnConfig"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="0.5"
android:text="#string/cpf_btnConfig" />
</LinearLayout>
</LinearLayout>
And here is the FragmentDialog:
package com.example.spendo.fragments;
imports....
public class CategoryPickerFragment extends DialogFragment implements OnItemClickListener{
private CategoryGroup categoryGroup;
private ListView lvCategorys;
private ArrayAdapter<String> lvAdapter;
private Button btnAddNew, btnConfig;
public CategoryPickerFragment() {
// Empty constructor required for DialogFragment
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_category_picker, container);
getDialog().setTitle("Hello");
categoryGroup = General.getActiveCategoryGroup(this.getActivity());
System.out.println(categoryGroup);
btnAddNew = (Button) this.getActivity().findViewById(R.id.btnAddNew);
btnConfig = (Button) this.getActivity().findViewById(R.id.btnConfig);
lvCategorys = (ListView) this.getActivity().findViewById(R.id.lvCategorys);
if(lvCategorys == null){ //this returns "lvCategorys is null"
System.out.println("lvCategorys is null");
}else{
System.out.println(lvCategorys + " is not null");
}
lvAdapter = new ArrayAdapter<String>(this.getActivity(),android.R.layout.simple_list_item_1, categoryGroup.getNameArray());
System.out.println(lvAdapter);
ArrayList<String> nameArray = categoryGroup.getNameArray();
lvAdapter.clear();
for(int i = 0; i < nameArray.size(); i++){
lvAdapter.add((String) nameArray.get(i));
}
lvAdapter.notifyDataSetChanged();
lvCategorys.setAdapter(lvAdapter);
return view;
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
}
}
Does anyone see my problem. (I'm quite new to android, altho i've done some java in the past).
//Sverker

I think you need to replace
btnAddNew = (Button) this.getActivity().findViewById(R.id.btnAddNew);
btnConfig = (Button) this.getActivity().findViewById(R.id.btnConfig);
lvCategorys = (ListView) this.getActivity().findViewById(R.id.lvCategorys);
with
btnAddNew = (Button) view.findViewById(R.id.btnAddNew);
btnConfig = (Button) view.findViewById(R.id.btnConfig);
lvCategorys = (ListView) view.findViewById(R.id.lvCategorys);

Related

dynamic add-view with ID

i am creating an application, which i use to create a list of things that i have in SQLite database
i created a Fragment with a button that add a xml file to my LinearLayout , it works good , but i want to grab EditText and Spinner data and put them in a JSONobject but i don't know how , i don't have IDs of dynamically created views
My Fragment XML
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:id="#+id/itemsContainer"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="50dp"
android:orientation="vertical"
android:paddingTop="20dp">
</LinearLayout>
</ScrollView>
<android.support.design.widget.FloatingActionButton
android:id="#+id/addItem"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_margin="16dp"
app:srcCompat="#drawable/fab_add"
/>
</RelativeLayout>
My field (addView) XML
<LinearLayout android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="horizontal"
android:weightSum="3"
xmlns:android="http://schemas.android.com/apk/res/android">
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_weight="1"
android:gravity="center_horizontal"
android:orientation="horizontal"
android:weightSum="2">
<Button
android:id="#+id/add"
android:onClick="onIncrease"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_gravity="center"
android:background="#drawable/ic_add_circle_black_24dp" />
<Button
android:id="#+id/remove"
android:onClick="onDecrease"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_gravity="center"
android:layout_marginLeft="10dp"
android:background="#drawable/ic_remove_circle_black_24dp" />
</LinearLayout>
<EditText
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:inputType="number"
android:hint="#string/number"
/>
<Spinner
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1" />
</LinearLayout>
Fragment.java File
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_newfactor,container,false);
fab = v.findViewById(R.id.addItem);
ln = v.findViewById(R.id.itemsContainer);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View rowView = inflater.inflate(R.layout.field, null);
final EditText editText = rowView.findViewById(R.id.number);
Button add = rowView.findViewById(R.id.add);
Button remove = rowView.findViewById(R.id.remove);
Button clear = rowView.findViewById(R.id.clear);
Spinner spinner = rowView.findViewById(R.id.spinner);
list = new ArrayList<>();
dbConnector = new DbConnector(getContext(),null,null,1);
Cursor c = dbConnector.get().rawQuery("SELECT * FROM product",null);
while (c.moveToNext()){
int id = c.getInt(c.getColumnIndex("id"));
String name = c.getString(c.getColumnIndex("name"));
String desc = c.getString(c.getColumnIndex("description"));
String price = c.getString(c.getColumnIndex("price"));
list.add(new SpinnerObject(id,name,price));
}
spinnerAdapter = new ir.animelist.localshop.Adaptors.SpinnerAdapter(getContext(),android.R.layout.simple_list_item_1,list);
spinner.setAdapter(spinnerAdapter);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int num = Integer.parseInt(editText.getText().toString());
int num_num = num + 1;
editText.setText(num_num + "");
}
});
remove.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int num = Integer.parseInt(editText.getText().toString());
if(num > 0){
int num_num = num - 1;
editText.setText(num_num + "");
}
}
});
clear.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ln.removeView((View) v.getParent());
}
});
ln.addView(rowView, ln.getChildCount() - 1);
}
});
return v;
}
You need to use the recyclerview to display your list items. Using recyclerview you can get view like -
View view = recyclerview.findViewHolderForAdapterPosition(pos).itemView;
Spinner spinner = view.findViewById(R.id.mySpinner);
This will return you a spinner of whichever position you have passed and afterwards get data from it.
Similarly, you can get view of edittext by using -
EditText edtTxt = view.findViewById(R.id.myEdtTxt);
To see how to get data from database and display that in recyclerview, check the example here - https://github.com/incipientinfo/db-queries

GridView buttons not working correctly

I have a GridView and am using a BaseAdapter to populate the values for each grid item. I am programmatically adding the buttons in each grid item using this adapter. The problem is, I have a total of SEVEN buttons. After each button click, the button is disabled so can only be clicked once.
So when the second button is clicked, the 7th button stops working. And if the 7th button is clicked, the first button stops working. The buttons are working fine and function properly apart from this.
EDIT: It seems like scrolling through the gridview (since the elements inside the gridview are large is causing the problem.)
Here is the relevant code.
MyAdapter.java
import static com.example.tuss.mafia.R.layout.layout_grid_item;
public class MyAdapter extends BaseAdapter {
Context context;
ArrayList<Players> playerList;
private static LayoutInflater inflater = null;
public MyAdapter(Context context, ArrayList<Players> playerList){
this.context = context;
this.playerList = playerList;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return playerList.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null)
convertView = inflater.inflate(layout_grid_item, null);
final Button button = (Button) convertView.findViewById(R.id.btnRoleReveal);
TextView idTextView = (TextView) convertView.findViewById(R.id.tv_player_id);
TextView nameTextView = (TextView) convertView.findViewById(R.id.tv_player_name);
final TextView roleTextView = (TextView) convertView.findViewById(R.id.tv_player_role);
Players p;
p = playerList.get(position);
idTextView.setText("ID: " + String.valueOf(p.getId()));
nameTextView.setText(String.valueOf(p.getName()));
roleTextView.setText("Your Role Is: " + String.valueOf(p.getRole())+ ", you won't be able to view this again.");
final String role = roleTextView.getText().toString();
button.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
new AlertDialog.Builder(context)
.setTitle("Remember your role and keep it a secret!")
.setMessage(role)
.create()
.show();
button.setEnabled(false);
button.setText("Role has been viewed");
return true;
}
});
return convertView;
}
}
The XML for the gridview, fragment_viewroles.xml
<RelativeLayout 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:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.tuss.mafia.GameActivity" >
<GridView
android:id="#+id/gv_players"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:numColumns="2"
android:stretchMode="columnWidth"
android:nestedScrollingEnabled="true"
android:columnWidth="150dp"
android:horizontalSpacing="10dp"
android:verticalSpacing="20dp"
android:textAlignment="center"
android:gravity="center">
</GridView>
</RelativeLayout>
layout_grid_item.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:background="#drawable/customborder"
android:orientation="vertical" >
<TextView
android:id="#+id/tv_player_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAlignment="center"
android:textColor="#android:color/white"
android:visibility="gone"
android:text="ID" />
<TextView
android:id="#+id/tv_player_name"
android:textAlignment="center"
android:textSize="35dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#android:color/holo_blue_bright"
android:text=""
android:textStyle="normal|bold" />
<TextView
android:id="#+id/tv_player_role"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAlignment="center"
android:clickable="true"
android:text="role"
android:visibility="invisible">
</TextView>
<Button
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="Hold to reveal your role"
android:id="#+id/btnRoleReveal"
/>
RolesFragment.java
public RolesFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_viewroles, container, false);
gridView = (GridView) view.findViewById(R.id.gv_players);
DatabaseHelper databaseHelper = new DatabaseHelper(getActivity());
playersList = new ArrayList<Players>();
playersList = databaseHelper.getPlayers();
adapter = new MyAdapter(getActivity(), playersList);
gridView.setAdapter(adapter);
return view;
}
replace button.setEnabled(false); with ((Button)v).setEnabled(false);
I think the problem is in your button event.
Just Initialize button event once
if (convertView == null){
convertView = inflater.inflate(layout_grid_item, null);
Button button = (Button) convertView.findViewById(R.id.btnRoleReveal);
button.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
Button btn = (Button)v;
new AlertDialog.Builder(context)
.setTitle("Remember your role and keep it a secret!")
.setMessage(role)
.create()
.show();
btn.setEnabled(false);
btn.setText("Role has been viewed");
return true;
}
});
}
Check this KodeCenter example

How to access listview items generated by ArrayAdapter by CLICKING ON BUTTON

I'm using a ListView with ArrayAdapter. There is a Button along with TextView in the listview.xml. I want to retrieve data from that TextView by Clicking over corresponding buttons.
My listview.xml is as follows:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
<TextView
android:id="#+id/label"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dip"
android:textSize="16dip"
android:textStyle="bold"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:layout_marginLeft="90dp"
android:id="#+id/btConfirmfriend"
android:text="Confirm Friend"
/>
</RelativeLayout>
My PendingRequest Class is as follows:
public class PendingRequest extends AddFriend {
TextView tvPending;
Button btConfirmfriend;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.pendingrequest);
final String[] s= getIntent().getExtras().getStringArray("pending");
System.out.println(s[1]);
final ListAdapter adapter = new ArrayAdapter<String>(this,R.layout.listview,R.id.label,s);
final ListView listView = (ListView) findViewById(R.id.mobile_list);
listView.setAdapter(adapter);
final View inflatedView = getLayoutInflater().inflate(R.layout.listview, null);
btConfirmfriend = (Button) inflatedView.findViewById(R.id.btConfirmfriend);
btConfirmfriend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ServerConnection sc = new ServerConnection();
//here I want to retrieve the value from List
//System.out.println(s[adapter.]);
int status = sc.confirmRequest(s[listView.getSelectedItemPosition()]);
AlertDialog.Builder alert = new AlertDialog.Builder(PendingRequest.this);
if (status == 1) {
alert.setMessage("Friend has been Added");
alert.show();
} else {
alert.setMessage("Sorry for inconvinient!!Try Again");
alert.show();
}
}
});
}
}
My pendingrequest.xml file is:-
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:background="#drawable/background"
android:layout_height="match_parent">
<Button
android:layout_marginTop="50dp"
android:layout_gravity="center"
android:layout_width="200dp"
android:layout_height="100dp"
android:background="#e9abab"
android:id="#+id/btSend"
android:text="Pending Requests"
/>
<ListView
android:id="#+id/mobile_list"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</ListView>
</LinearLayout>
On clicking over the button nothing happening.onClick() method is not executing.Please help.
Since you need a click listener on a view inside your list item, you need to write your own adapter for that -
class CustomAdapter extends ArrayAdapter<String> {
public CustomAdapter(Context context, String[] list) {
super(context, 0, list);
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// Get the data item for this position
String item = getItem(position);
// Check if an existing view is being reused, otherwise inflate the view
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.list_item, parent, false);
}
// Lookup view for data population
TextView label = (TextView) convertView.findViewById(R.id.label);
Button btConfirmfriend = (Button) convertView.findViewById(R.id.btConfirmfriend);
// Populate the data into the template view using the data object
label.setText(item);
btConfirmfriend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getItem(position); //Get your selected text
}
});
return convertView;
}
}
And this is how you will set the adapter -
final CustomAdapter adapter = new CustomAdapter(this,s);
final ListView listView = (ListView) findViewById(R.id.mobile_list);
listView.setAdapter(adapter);

Show my Fragment in Dialog android

I have a class that extends a Fragment. I want when press a button from An Activity to opens this Fragment with its layout in dialog in addition to that the fragment opens normally in its place. Is this possible?
This is my Fragment (TipsFragment.java)
public class TipsFragment extends Fragment{
ListView list;
TipsAdapter tipsAdapter;
AlertDialog PageDialog;
DAO db;
Cursor c;
ArrayList<HashMap<String, String>> tipsList;
HashMap<String, String> map;
ArrayList<HashMap<String, String>> pages;
Integer tipType;
ImageButton page;
ImageButton add;
ImageButton search;
EditText inputAdd;
EditText inputSearch;
ImageView addImage;
RelativeLayout layoutAdd;
RelativeLayout layoutSearch;
int itemSelected;
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
db = new DAO(activity);
db.open();
}
public TipsFragment(){}
public TipsFragment(int tipType, int itemSelected ){
this.tipType = tipType;
this.itemSelected = itemSelected;
}
#Override
public View onCreateView(final LayoutInflater inflater, final ViewGroup container,
final Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.tips_fragement, container, false);
System.out.println("tipType: "+tipType);
System.out.println("itemSelected: "+itemSelected);
page = (ImageButton) rootView.findViewById(R.id.pager);
add = (ImageButton) rootView.findViewById(R.id.add);
search = (ImageButton) rootView.findViewById(R.id.search);
inputSearch = (EditText) rootView.findViewById(R.id.inputSearch);
inputAdd = (EditText) rootView.findViewById(R.id.inputAdd);
addImage = (ImageView) rootView.findViewById(R.id.imageAdd);
layoutAdd = (RelativeLayout) rootView.findViewById(R.id.layoutAdd);
layoutSearch = (RelativeLayout) rootView.findViewById(R.id.layoutSearch);
if (tipType != 0) {
switch (tipType) {
case 1:
System.out.println("All tips");
if (getActivity().getIntent().getStringExtra("startFrom") == null) {
c = db.getTips("0");
} else {
c = db.getTips(getActivity().getIntent().getStringExtra("startFrom"));
}
break;
case 2:
System.out.println("favorite tips");
c = db.getFavoriteTips();
page.setVisibility(View.GONE);
System.out.println("in favorite, count_records: "+c.getCount());
break;
}
}
System.out.println("count_records: "+c.getCount());
if (c.getCount() != 0) {
if (getActivity().getIntent().getStringExtra("startLabel") != null) {
page = (ImageButton) rootView.findViewById(R.id.pager);
}
tipsList = new ArrayList<HashMap<String, String>>();
list = (ListView) rootView.findViewById(R.id.tipList);
do {
map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(DAO.TIP_ID, c.getString(c.getColumnIndex(c.getColumnName(0))));
map.put(DAO.TIP_CONTENT, c.getString(c.getColumnIndex(c.getColumnName(1))));
// adding HashList to ArrayList
tipsList.add(map);
} while (c.moveToNext());
// Getting adapter by passing xml data ArrayList
tipsAdapter = new TipsAdapter(getActivity(), tipsList);
list.setAdapter(tipsAdapter);
// Click event for single list row
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
map = tipsList.get(position);
System.out.println("in list select item, tipType: "+tipType);
if (!MainActivity.tSlidingLayer.isOpened()) {
MainActivity.tSlidingLayer.openLayer(true);
}
}
});
page.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Strings to Show In Dialog with Radio Buttons
}
});
add.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
}
});
search.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
}
});
inputSearch.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
});
}
addImage.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(getActivity(), "addImage pressed", Toast.LENGTH_LONG).show();
}
});
return rootView;
}
}
and this is layout tips_fragement.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:ads="http://schemas.android.com/apk/lib/com.google.ads"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_marginLeft="10dp"
android:layout_marginRight="5dp"
android:orientation="vertical" >
<LinearLayout
android:id="#+id/titleBar"
android:layout_width="match_parent"
android:layout_height="50dp"
android:gravity="center"
android:orientation="horizontal" >
<ImageButton
android:id="#+id/add"
android:layout_width="45dp"
android:layout_height="35dp"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:scaleType="fitXY"
android:src="#drawable/add" />
<ImageButton
android:id="#+id/search"
android:layout_width="45dp"
android:layout_height="35dp"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:scaleType="fitXY"
android:src="#drawable/search" />
<ImageButton
android:id="#+id/pager"
android:layout_width="45dp"
android:layout_height="35dp"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:scaleType="fitXY"
android:src="#drawable/pager" />
</LinearLayout>
<View
android:layout_width="fill_parent"
android:layout_height="5dip"
android:background="#drawable/shadow" >
</View>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/layoutAdd"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="gone" >
<EditText
android:id="#+id/inputAdd"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="Add" />
<ImageView
android:id="#+id/imageAdd"
android:padding="5dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/inputAdd"
android:layout_alignBottom="#+id/inputAdd"
android:layout_alignRight="#+id/inputAdd"
android:src="#android:drawable/ic_menu_add" />
</RelativeLayout>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/layoutSearch"
android:visibility="gone" >
<EditText
android:id="#+id/inputSearch"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="Search"/>
<ImageView
android:id="#+id/imageSearch"
android:padding="5dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/inputSearch"
android:layout_alignBottom="#+id/inputSearch"
android:layout_alignRight="#+id/inputSearch"
android:src="#android:drawable/ic_menu_search" />
</RelativeLayout>
<ListView
android:id="#+id/tipList"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/buttons"
android:divider="#351802"
android:dividerHeight="2dp"
android:listSelector="#drawable/list_selector" />
</LinearLayout>
Since Android supports nesting Fragments (available in the support library) you could show your TipsFragment as a content of another DialogFragment. Avoid this solution whenever possible.
A better solution would be to make TipsFragment extend DialogFragment and that way you can either show the Fragment inline or in a dialog.
1 - Make TipsFragment extends DialogFragment
public class TipsFragment extends DialogFragment {...}
2 - On button click use FragmentTransaction.add or FragmentTransaction.replace to show the DialogFragment inline or include it in your layout and change its visibility.
3 - Show the TipsFragment as a dialog
TipsFragment fr = new TipsFragment();
fr.show(getSupportFragmentManager(), "dialog_fragment_tag");
Guide: Performing Fragment Transactions. More samples are available in the ApiDemos application from the SDK samples

Android: archiving items in listview

I'm having a listview in which I'm displaying the text items. I want to display a checkbox along with the text for two type of actions to be performed. one is when the user click on the list item it should take to another activity and another is the user can select the checkbox of the list item and can move the items to some groups. As similar to that we do in the gmail inbox. how can i do it ? Any help ?
Here I attach my code.
keywords.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/keywordlayout"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#drawable/background_gradient"
android:orientation="vertical"
>
<LinearLayout
android:id="#+id/category_title_layout"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:background="#fff"
>
<TextView
android:id="#+id/category_title"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text=""
android:textColor="#000"
android:textStyle="italic"
android:typeface="sans"
android:gravity="center"
/>
</LinearLayout>
<ListView
android:id="#+id/keywordslist"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#drawable/background_gradient"
>
</ListView>
</LinearLayout>
The xml file used for displaying list items layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/list_display"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
>
<CheckBox
android:id="#+id/chk_box"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:visibility="invisible"
>
</CheckBox>
<TextView
android:id="#+id/key_id"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
>
</TextView>
<TextView
android:id="#+id/key_name"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dp"
android:textSize="16sp"
android:textColor="#FFF">
</TextView>
</LinearLayout>
and my java code for the activity
package com.sample.epiphron;
public class KeywordsList extends Activity {
TextView category_title;
ListView keywords_list ;
String categoryid, categoryname;
private ArrayList<KeywordDetails> listItems = new ArrayList<KeywordDetails>();
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.keywords);
Bundle extras = getIntent().getExtras();
categoryid = extras.getString("category_id");
categoryname = extras.getString("category_name");
category_title = (TextView) findViewById(R.id.category_title);
category_title.setText(""+categoryname+"- Keywords");
keywords_list = (ListView) findViewById(R.id.keywordslist);
drawList(LoginScreen.user_credential, categoryid);
//Toast.makeText(this, chkbx.toString(), Toast.LENGTH_SHORT).show();
keywords_list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
TextView txtv1 = (TextView) arg1.findViewById(R.id.key_id);
Toast.makeText(KeywordsList.this, txtv1.getText(), Toast.LENGTH_LONG).show();
}
});
}
public void drawList(String userid, String cat_id){
WebServiceCall res = new WebServiceCall();
SoapObject result = res.fetchKeyword(userid, cat_id);
ArrayList<String> al = new ArrayList<String>();
for (int i = 0; i<result.getPropertyCount(); i++){
SoapObject obj = (SoapObject) result.getProperty(i);
al.add((String) obj.getProperty("keywordname"));
KeywordDetails object = new KeywordDetails(Integer.parseInt(obj.getProperty("keywordid").toString()), obj.getProperty("keywordname").toString());
listItems.add(object);
}
for ( int j = 0; j < result.getPropertyCount(); j++ ) {
}
keywords_list.setAdapter(new ListItemsAdapter(listItems));
}
public class KeywordDetails{
private int keyword_id;
private String keyword_name;
public KeywordDetails(int key_id, String key_name){
this.keyword_id = key_id;
this.keyword_name = key_name;
}
public int getId(){
return this.keyword_id;
}
public String getName(){
return this.keyword_name;
}
//...
}
private class ListItemsAdapter extends ArrayAdapter<KeywordDetails> {
ArrayList<KeywordDetails> obj = null;
KeywordDetails keyworddtls = null;
public ListItemsAdapter(ArrayList<KeywordDetails> items) {
super(KeywordsList.this, android.R.layout.simple_list_item_1, items);
this.obj = items;
}
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = getLayoutInflater();
convertView = inflater.inflate(R.layout.keyword_list_item, null);
final TextView text1 = (TextView) convertView.findViewById(R.id.key_id);
TextView text2 = (TextView) convertView.findViewById(R.id.key_name);
CheckBox chkbx = (CheckBox) convertView.findViewById(R.id.chk_box);
keyworddtls = obj.get(position);
text1.setText(Integer.toString(keyworddtls.getId()));
text2.setText(keyworddtls.getName());
chkbx.setVisibility(View.VISIBLE);
return convertView;
}
}
}
Add the CheckBox in the xml where is your <ListView > or in the xml which you use as item layout. Then in the getView() instantiate the CheckBox along the TextView. Implement listview.setOnItemClickListener() and based on which item was clicked (position) you start the activity [matter of logic] For the grouped of check items you can use getCheckedItemPositions(). I hope this will give you fire up idea.

Categories

Resources