dynamic add-view with ID - android

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

Related

custom view with overlapping

I define layout row which I inflate and add view pragmatically to a linear layout.
I wanna something like this,
https://i.stack.imgur.com/EKPmJ.png
Here is xml of my main activity where I am inflating the costume view row
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
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"
android:orientation="vertical"
tools:context="com.skw.customeviewdemo.MainActivity">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/inflate"
android:text="inflate"/>
<LinearLayout
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/list_container">
</LinearLayout>
</LinearLayout>
here is my xml code of row which I am inflating:
<?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"
android:orientation="horizontal">
<TextView
android:id="#+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:text="its text view"
/>
<Button
android:id="#+id/nameButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/name"
/>
<ImageView
android:layout_marginTop="-25dp"
android:layout_alignParentRight="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#mipmap/ic_launcher_round"/>
</RelativeLayout>
here is my java code
public class MainActivity extends AppCompatActivity {
Button b;
LinearLayout l1;
Context context;
Boolean isViewCreated = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final String Namearray[] = {"sagar", "ranjeet", "akash", "kate"};
this.context = this;
b = (Button) findViewById(R.id.inflate);
l1 = (LinearLayout) findViewById(R.id.list_container);
createViews(Namearray);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(l1.getVisibility() == View.VISIBLE && isViewCreated)
{
l1.setVisibility(View.GONE);
}
else
{
l1.setVisibility(View.VISIBLE);
}
}
});
}
void createViews(final String[] namearray)
{
for(int i=0;i < namearray.length;i++){
final int j = i;
View view = LayoutInflater.from(context).inflate(R.layout.layout_item,null);
TextView button1 = (TextView) view.findViewById(R.id.name);
Button button2 = (Button) view.findViewById(R.id.nameButton);
button1.setText("HELLO " + namearray[i]);
button2.setText("Click to know my name ");
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context,"Hello " + namearray[j],Toast.LENGTH_LONG).show();
}
});
view.setId(generateViewId());
try {
l1.addView(view);
isViewCreated = true;
}
catch (Exception e)
{
}
}
l1.setVisibility(View.GONE);
}
private static final AtomicInteger viewIdGenerator = new AtomicInteger(15000000);
public static int generateViewId() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) {
return generateUniqueViewId();
} else {
return View.generateViewId();
}
}
private static int generateUniqueViewId() {
while (true) {
final int result = viewIdGenerator.get();
// aapt-generated IDs have the high byte nonzero; clamp to the range under that.
int newValue = result + 1;
if (newValue > 0x00FFFFFF) newValue = 1; // Roll over to 1, not 0.
if (viewIdGenerator.compareAndSet(result, newValue)) {
return result;
}
}
}
}
but when I inflate row my image view get cutoff which I not want I tried with negative margin but it not work
here what it looks like
custom overlapping row
what I do so I over lap image to above view?
Try changing your layout to this.
<?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"
android:orientation="horizontal">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:text="its text view"
/>
<Button
android:id="#+id/nameButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/name"
/>
</RelativeLayout>
<ImageView
android:layout_marginTop="25dp"
android:layout_alignParentRight="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#mipmap/ic_launcher_round"/>
</RelativeLayout>
When you put in another row, that row needs to be pushed up so the android icon that is there now overlays it.

setOnItemClickListener not working in Fragment

I am trying to change the text and check box response of the clicked list item but I am not able to do so. As I not able to get the clicked list item.
The fragment is a part of view pager.
Here is my code,
public class ParticipantsFragment extends Fragment {
private ParticipantAdapter mAdapter;
SwipeRefreshLayout refreshLayout;
private String mParticipantId, mEventId, mGender;
ParticipantsAsyncTask task;
public ParticipantsFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mEventId = getArguments().getString(Config.BUNDLE_KEY_EVENT_ID);
mParticipantId = getArguments().getString(Config.BUNDLE_KEY_PARTICIPANT_ID);
mGender = getArguments().getString(Config.BUNDLE_KEY_GENDER);
Log.v("fragh", mEventId + " " + mParticipantId);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.participant_list, container, false);
TextView textView = (TextView) rootView.findViewById(R.id.no_participant);
task = new ParticipantsAsyncTask();
task.execute();
ListView participantListView = (ListView) rootView.findViewById(R.id.participant_list);
refreshLayout = (SwipeRefreshLayout) rootView.findViewById(R.id.swipe_refresh_layout_participant_list);
participantListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.v("Clicked Participant",mAdapter.getItem(position).getParticipantName());
EditText notes = (EditText) rootView.findViewById(R.id.participant_list_item_notes);
String text = notes.getText().toString();
Log.v("Participant Text",text);
CheckBox checkBox = (CheckBox) rootView.findViewById(R.id.participant_list_item_checkbox);
String check;
if(checkBox.isChecked())
{
check = "1";
}
else
{
check = "0";
}
}
});
Button submit = (Button) rootView.findViewById(R.id.submit_participant);
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
mAdapter = new ParticipantAdapter(getContext(), new ArrayList<Participant>());
participantListView.setAdapter(mAdapter);
participantListView.setEmptyView(textView);
refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
task = new ParticipantsAsyncTask();
task.execute();
refreshLayout.setRefreshing(false);
}
});
return rootView;
}
private class ParticipantsAsyncTask extends AsyncTask<Void, Void, List<Participant>> {
private ProgressDialog progress;
#Override
protected void onPreExecute() {
progress = new ProgressDialog(getContext());
progress.setMessage("Gathering Data...");
progress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progress.setIndeterminate(true);
progress.setCancelable(false);
progress.show();
}
#Override
protected void onPostExecute(List<Participant> data) {
// Clear the adapter of previous participant data
mAdapter.clear();
// If there is a valid list of {#link Event}s, then add them to the adapter's
// data set. This will trigger the ListView to update.
if (data != null && !data.isEmpty()) {
mAdapter.addAll(data);
}
}
#Override
protected List<Participant> doInBackground(Void... params) {
List<Participant> result;
if (!mGender.isEmpty()) {
HashMap<String, String> map = new HashMap<String, String>();
map.put(Config.KEY_EVENT_ID, mEventId);
map.put(Config.KEY_PARTICIPANT_ID, mParticipantId);
map.put(Config.KEY_GENDER, mGender);
result = QueryUtils.extractParticipantData(map, Config.FEVER_GENDER_FILTER_PARTICIPANT_URL);
} else {
HashMap<String, String> map = new HashMap<String, String>();
map.put(Config.KEY_EVENT_ID, mEventId);
map.put(Config.KEY_PARTICIPANT_ID, mParticipantId);
Log.v("law", mEventId + ", " + mParticipantId);
result = QueryUtils.extractParticipantData(map, Config.FEVER_ALL_PARTICIPANT_URL);
}
progress.dismiss();
return result;
}
}
#Override
public void onDestroyView() {
super.onDestroyView();
mAdapter.clear();
}
}
participant_list.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">
<TextView
android:id="#+id/no_participant"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="16dp"
android:gravity="center_horizontal"
android:text="#string/no_participant_found"
android:textColor="#color/primaryText"
android:textSize="24sp"
android:visibility="gone" />
<android.support.v4.widget.SwipeRefreshLayout
android:id="#+id/swipe_refresh_layout_participant_list"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1">
<ListView
android:id="#+id/participant_list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:divider="#color/divider"
android:dividerHeight="1dp"
android:descendantFocusability="beforeDescendants"
android:drawSelectorOnTop="true"
android:headerDividersEnabled="true" />
</android.support.v4.widget.SwipeRefreshLayout>
<Button
android:id="#+id/submit_participant"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Submit"
android:textSize="20sp"
android:background="#color/colorAccent"/>
</LinearLayout>
participant_list_item.xml
<?xml version="1.0" encoding="utf-8"?>
<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="80dp"
android:clickable="true"
android:descendantFocusability="beforeDescendants"
android:focusableInTouchMode="true"
android:orientation="horizontal"
android:padding="8dp">
<TextView
android:id="#+id/participant_list_item_id"
android:layout_width="0dp"
android:textStyle="bold"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_weight="2"
android:textSize="20sp"
tools:text="M78" />
<TextView
android:id="#+id/participant_list_item_name"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_marginLeft="8dp"
android:layout_marginStart="8dp"
android:layout_weight="5"
android:textSize="20sp"
android:fontFamily="sans-serif"
tools:text="Billu Barber" />
<EditText
android:id="#+id/participant_list_item_notes"
android:layout_width="0dp"
android:layout_height="60dp"
android:layout_gravity="center_vertical"
android:layout_marginLeft="16dp"
android:layout_marginStart="16dp"
android:layout_weight="6"
android:textSize="12sp"
android:background="#drawable/participant_list_notes"
android:hint="#string/participant_notes"
android:inputType="textMultiLine"
android:scrollbars="none"
android:imeOptions="actionDone"
android:maxLength="50"
android:padding="4dp" />
<CheckBox
android:id="#+id/participant_list_item_checkbox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_marginLeft="16dp"
android:layout_marginStart="16dp" />
</LinearLayout>
Found the answer atlast.
Don't use setOnItemClickListener for item click. Use item view click inside adapter method by using setOnClickListener(). Do things in onClick()
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
View listItemView = convertView;
if (listItemView == null)
{
listItemView = LayoutInflater.from(getContext()).inflate(R.layout.participant_list_item, parent, false);
}
listItemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
Toast.makeText(mContext, "click item",Toast.LENGTH_LONG).show();
}
});
Participant currentParticipant = getItem(position);
if(currentParticipant.getParticipantGender().equals("F"))
{
TextView idView = (TextView) listItemView.findViewById(R.id.participant_list_item_id);
idView.setTextColor(getColor(mContext, R.color.colorPrimary));
idView.setText(currentParticipant.getParticipantId());
}
else if(currentParticipant.getParticipantGender().equals("M"))
{
TextView idView = (TextView) listItemView.findViewById(R.id.participant_list_item_id);
idView.setTextColor(getColor(mContext, R.color.colorAccent));
idView.setText(currentParticipant.getParticipantId());
}
TextView nameView = (TextView) listItemView.findViewById(R.id.participant_list_item_name);
nameView.setText(currentParticipant.getParticipantName());
final EditText notesView = (EditText) listItemView.findViewById(R.id.participant_list_item_notes);
notesView.setText(currentParticipant.getParticipantNotes());
CheckBox checkedView = (CheckBox) listItemView.findViewById(R.id.participant_list_item_checkbox);
if (currentParticipant.getParticipantCheck().equals("1"))
{
checkedView.setChecked(true);
}
else
{
checkedView.setChecked(false);
}
return listItemView;
}
Remove this from participant_list_item.xml
android:descendantFocusability="blocksDescendants"
Thank you every one for the help.
<CheckBox
android:id="#+id/participant_list_item_checkbox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:focusable="false"
android:clickable="false"
android:layout_marginLeft="16dp"
android:layout_marginStart="16dp" />
Try to replace your CheckBox and add this two line
android:focusable="false"
android:clickable="false"
Try this should work in participant_list_item.xml and remove from listview
android:descendantFocusability="blocksDescendants"
you have to do it like this
private EditText notes;
private CheckBox checkBox;
and put these above onclick
notes = (EditText) rootView.findViewById(R.id.participant_list_item_notes);
String text = notes.getText().toString();
Log.v("Participant Text",text);
checkBox = (CheckBox) rootView.findViewById(R.id.participant_list_item_checkbox);
edittext and check box are the view in the listview
hope this will help you
android:clickable=true
Make sure that you have added clickable property to true.
In participantslist.xml file:
<ListView
android:id="#+id/participant_list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:divider="#color/divider"
android:dividerHeight="1dp"
android:descendantFocusability="beforeDescendants"
android:drawSelectorOnTop="true"
android:headerDividersEnabled="true"
android:clickable=true/>
And let me know if this suggestion was wrong?

Android Listview button doesn't work

I created a custom listview with the base adapter, but for some reason can not click on the button inside the individual list views.
Here is the code the the main layout:
<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:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Light List"
android:id="#+id/lightName"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/loginbutton"
android:id="#+id/button"
android:onClick="buttonClicked"
android:layout_alignParentBottom="true"
android:layout_alignLeft="#+id/lightName"
android:layout_alignStart="#+id/lightName" />
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/lightList"
android:layout_below="#+id/lightName"
android:layout_above="#+id/button"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"/>
</RelativeLayout>
Here is the code for views in the list:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/lightList"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Medium Text"
android:id="#+id/lightName"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Text"
android:id="#+id/statusText"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Button"
android:id="#+id/buttonoff"
android:focusable="true"
android:enabled="true"
android:clickable="true" />
</LinearLayout>
Lastly here is the adapter code:
public ArrayList<myLight> dataSet = new ArrayList<myLight>();
public void makeLightList(ArrayList<myLight> lights) {
Iterator<myLight> iter = lights.iterator();
while(iter.hasNext()) {
dataSet.add(iter.next());
}
}
#Override
public int getCount() {
return dataSet.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View v;
LayoutInflater inflater = (LayoutInflater)getBaseContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = inflater.inflate(R.layout.lightlistlayout, null);
TextView name = (TextView) findViewById(R.id.lightName);
name.setText(dataSet.get(position).name);
TextView status = (TextView) findViewById(R.id.statusText);
if(dataSet.get(position).reachable) {
if(dataSet.get(position).isOn) {
status.setText("Light is On");
} else {
status.setText("Light is Off");
}
} else {
status.setText("Light is currently not reachable");
}
dataHolder dh = new dataHolder();
dh.name = dataSet.get(position).name;
//Handle Off button click from list view
Button offButton = (Button) findViewById(R.id.buttonoff);
offButton.setTag(dh);
offButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
dataHolder dhv = new dataHolder();
dhv = (dataHolder)v.getTag();
Toast.makeText(getBaseContext(), dhv.name + " Turned Off", Toast.LENGTH_LONG).show();
}
});
return v;
}
};
I am not sure if my onclicklistener is correct as I can't click on the button at all yet. Here is a picture showing the button. I have messed with different focus and clickable settings in the xml file and no luck. I added a seeker bar that I was able to slide that back and forth, but the button will not let me click it.
v = inflater.inflate(R.layout.lightlistlayout, null);
Here you have inflated the row file for your adapter and the below are your id initialization and for that you have not added your view to your id, so try this.
TextView name = (TextView) v.findViewById(R.id.lightName);
TextView status = (TextView) v.findViewById(R.id.statusText);
Button offButton = (Button) v.findViewById(R.id.buttonoff);
try changing
android:focusable="true" to android:focusable="false" in Button's xml

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

ListView declared in layout is null in onCreateView

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);

Categories

Resources