listview items not showing up in android - android

I am beginner in Android application development and there might be similiar question on stackoverflow but I am unable to find the exact solution to this problem.I have tried many links on SO. Help Appreciated. Let me know if any other file needs to be uploaded.
Here is the listview output
Listview output
I'm pretty sure the items are inserted in the listview because I get the following output when i toast the item at 0.Toast.makeText to display item0 of listview l1
So no problem with inserting data into listview. the problem probably is in displaying
// fragment_cart layout - where the listview is stored.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/listview_cart"
/>
</LinearLayout>
Cartlist_layout - the structure of listview
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</TextView>
//addtocart_layout
<?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="vertical">
<TextView
android:text="Total : Rs"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/textView10"
android:textSize="20sp"
android:textStyle="normal|bold"
android:layout_marginTop="16dp"
android:layout_below="#+id/textView9"
android:layout_alignStart="#+id/textView9" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="number"
android:ems="4"
android:id="#+id/editText6"
android:text="1"
android:layout_alignBaseline="#+id/textView9"
android:layout_alignBottom="#+id/textView9"
android:layout_alignStart="#+id/textView11" />
<TextView
android:text="0"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/textView11"
android:textStyle="normal|bold"
android:textSize="20sp"
android:layout_alignBaseline="#+id/textView10"
android:layout_alignBottom="#+id/textView10"
android:layout_alignParentEnd="true"
android:layout_marginEnd="142dp" />
<TextView
android:text="Quantity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/textView9"
android:textSize="20sp"
android:textStyle="normal|bold"
android:layout_marginTop="36dp"
android:layout_below="#+id/textView7"
android:layout_toStartOf="#+id/textView11"
android:layout_marginEnd="45dp" />
<TextView
android:text="ItemName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/textView7"
android:textStyle="normal|bold"
android:textSize="20sp"
android:layout_marginTop="95dp"
android:layout_alignParentTop="true"
android:layout_toEndOf="#+id/textView10"
android:layout_marginStart="12dp" />
</RelativeLayout>
CartDialog - the java file
public class CartDialog extends DialogFragment {
String item;
TextView iname,t11;
EditText qty;
LayoutInflater inflater;
View view;
NumberPicker numberPicker;
public static int sprice[]={40,50,60,25,30,30,25,25,20,20,20,15,15};
public String names[]=new String[]{"Item1","Item2","Item3"};
public ListView l1;
int i=0;
List itemName;
LinearLayout rl;
#NonNull
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
inflater=getActivity().getLayoutInflater();
itemName=new ArrayList();
view=inflater.inflate(R.layout.addtocart_layout,null);
rl = (LinearLayout)view.inflate(this.getContext(), R.layout.fragment_cart,null);
//#s1 This code is for some other functionality.
iname=(TextView)view.findViewById(R.id.textView7);
iname.setText(MyMenu.item1);
int id=Integer.parseInt(MyMenu.childid);
qty=(EditText)view.findViewById(R.id.editText6);
t11=(TextView)view.findViewById(R.id.textView11);
t11.setText(Integer.toString(Integer.parseInt(qty.getText().toString())*sprice[id]));
qty.addTextChangedListener(
new TextWatcher() {
int id=Integer.parseInt(MyMenu.childid);
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
String qty_value=qty.getText().toString();
if(!qty_value.equals(""))
t11.setText(Integer.toString(Integer.parseInt(qty_value)*sprice[id]));
else
t11.setText("");
}
}
);
#s1 ends here
AlertDialog.Builder builder=new AlertDialog.Builder(getActivity());
builder.setView(view).setPositiveButton("Add to Cart", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
onAddToCart();
}
}).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
return builder.create();
}
public void onAddToCart(){
//PLAUSIBLE PROBLEM HERE - i think, Something must be wrong here
ArrayAdapter<String> adapter1=new ArrayAdapter<String>(this.getContext(),R.layout.cartlist_layout,names);
l1=(ListView)rl.findViewById(R.id.listview_cart);
l1.setAdapter(adapter1);
Toast.makeText(this.getContext(),"Added to Cart:"+l1.getItemAtPosition(0),Toast.LENGTH_SHORT).show();
}
}

When you inflate your fragment_cart layout you are not attaching it to anything, that's why you can't see your results.
From the image you showed, it seems that the fragment_cart layout is actually part of the activity.
You could do something like this
Main Activity
public class MainActivity extends Activity {
public Fragment mCartFragment;
//...
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//...
mCartFragment = new CartFragment();
// Attach this fragment to your main activity
}
}
Cart Fragment
public class CartFragment extends Fragment {
View mView;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle s) {
// inflate fragment_cart here
mView = inflater.inflate(
R.layout.fragment_cart,
container,
false
);
return mView;
}
}
And in your addToCart() method (assuming MainActivity is responsible for launching the CartDialog):
public void addToCart(){
MainActivity mainActivity = (MainActivity)getActivity();
View fragmentCartView = mainActivity.mCartFragment.getView();
if(fragmentCartView != null){
ArrayAdapter<String> adapter1=new ArrayAdapter<String>(this.getContext(),R.layout.cartlist_layout,names);
l1 = fragmentCartView.findViewById(R.id.listview_cart);
l1.setAdapter(adapter1);
Toast.makeText(this.getContext(),"Added to Cart:"+l1.getItemAtPosition(0),Toast.LENGTH_SHORT).show();
}
}
Now, I don't like this solution very much because you are coupling the CartDialog to the main activity, but I didn't want to change your code too much.

Try to add this in your method :
adapter1.notifyDataSetChanged();

Related

Custom List Fragment disabling clicks to element and enabling button clicks(Android Studio)

I know they are similar questions but I could not make them work. I have a list fragment which includes the item in my array list and a button next to it for each element in my array list. My ultimate goal is to make program respond only when the user clicks to button but I could not even manage to detect the clicks on the screen. I also tried setting button's focusable to false(suggested from other questions) but that also did not work. Here is my code.
public class ResultListFragment extends ListFragment {
private List<String> listValues, keyValues;
private String email, username;
private ArrayAdapter<String> myAdapter;
private ListView myListView;
private TextView title;
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_resultlist, container, false);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
View v = getView();
myListView = getListView();
listValues = new ArrayList<String>();
myAdapter = new ArrayAdapter<String>(getActivity().getApplicationContext(),
R.layout.fragment_rowlayout, R.id.myListText, CameraActivity.resultList);
setListAdapter(myAdapter);
myAdapter.notifyDataSetChanged();
}
#Override
public void onListItemClick(ListView l, View v, final int position, long id) {
super.onListItemClick(l, v, position, id);
Log.d("blabla", "onListItemClick: clicked to : "+position);
final String delete=CameraActivity.resultList.get(position);
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setCancelable(true);
builder.setTitle("DELETION");
builder.setMessage(delete + " delete it.");
builder.setPositiveButton("Onayla",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getActivity().getApplicationContext(), delete+ "has been deleted", Toast.LENGTH_SHORT).show();
CameraActivity.resultList.remove(position);
myAdapter.notifyDataSetChanged();
for(String st:CameraActivity.resultList){
Log.d("TAG", "onClick: eleman: " +st);
}
}
});
builder.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
}
Here are my xml files
fragment result list
<?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:paddingLeft="8dp"
android:paddingRight="8dp">
<ListView android:id="#id/android:list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:drawSelectorOnTop="false"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="8dp"
android:background="#drawable/cembutton"
android:text="Yükle"
android:id="#+id/load"
android:layout_alignRight="#+id/results"
android:focusable="false"
android:focusableInTouchMode="false"
android:layout_alignParentBottom="true"
android:textColor="#ffffff"
android:textStyle="bold"/>
<TextView android:id="#id/android:empty"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="No data"/>
</RelativeLayout>
and fragment_rowlayout
<?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:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
>
<TextView
android:id="#+id/myListText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="16dp"
android:layout_marginTop="16dp"
android:textStyle="bold"
android:textColor="#3700ff" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:drawable="#drawable/cembutton"
android:layout_alignParentRight="true"
android:text="Çıkart"
android:layout_marginRight="50dp"/>
</RelativeLayout>
You should provide custom adapter for your listview.
Then, in getView() method you can find your button by id and set onClickListener to it.

Android Spinner resizing when selecting

In mi layout I have 3 spinners. Each one implements onItemSelectedListener. The problem is when I select an option on spinner number 2 (spinnerSwitches) the spinner number 3 (spinnerVQs) is resizing itself, and i don´t want that to happen.
I attached, Activity code, images, and xml layout
Activity:
public class CCHawkResourcesActivity extends Activity {
private Spinner spinnerTenants;
private Spinner spinnerSwitches;
private Spinner spinnerVQs;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cchawk_resources);
vincularControles();
Sesion.setUsuarioActual(RetornaLogica.GetInstance().getIl().TraerUsuarios().get(0));
Tenant selectedTenant=new Tenant(Sesion.getUsuarioActual().getConfig().getSelectedTenant());
ArrayAdapter<Tenant> a=new ArrayAdapter<Tenant>(this,R.layout.spinner_dropdown_item,Sesion.getListaTenants());
a.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerTenants.setAdapter(a);
if(!selectedTenant.getNombre().equals(""))spinnerTenants.setSelection(a.getPosition(selectedTenant));
spinnerTenants.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View selectedView,int position, long id) {
Tenant t=((Tenant)spinnerTenants.getSelectedItem());
Switch selectedSwitch=new Switch(Sesion.getUsuarioActual().getConfig().getSelectedSwitch());
ArrayAdapter<Switch> b=new ArrayAdapter<Switch>(CCHawkResourcesActivity.this,R.layout.spinner_dropdown_item,t.getListaSwitch());
b.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerSwitches.setAdapter(b);
if(!selectedSwitch.getNombre().equals(""))spinnerSwitches.setSelection(b.getPosition(selectedSwitch));
spinnerSwitches.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View selectedView,int position, long id) {
Switch s=((Switch)spinnerSwitches.getSelectedItem());
VirtualQueue selectedVQ=new VirtualQueue(Sesion.getUsuarioActual().getConfig().getSeletedVQ());
ArrayAdapter<VirtualQueue> c=new ArrayAdapter<VirtualQueue>(CCHawkResourcesActivity.this,R.layout.spinner_dropdown_item,s.getListaVQ());
c.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerVQs.setAdapter(c);
if(!selectedVQ.getNombre().equals(""))spinnerVQs.setSelection(c.getPosition(selectedVQ));
spinnerVQs.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View selectedView,int position, long id) {}
#Override
public void onNothingSelected(AdapterView<?> arg0) {}
});
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {}
});
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {}
});
}
private void vincularControles(){
spinnerTenants=(Spinner)findViewById(R.id.spinnerTenants);
spinnerSwitches=(Spinner)findViewById(R.id.spinnerSwitches);
spinnerVQs=(Spinner)findViewById(R.id.spinnerVQs);
}
}
Activity Layout
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/extra_dark_grey"
android:orientation="vertical"
android:padding="20dp" >
<TextView
android:id="#+id/select"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingBottom="5dp"
android:text="#string/select"
android:textColor="#color/skyblue"
android:textSize="25sp"
android:textStyle="bold" />
<TextView
android:id="#+id/selectText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingBottom="20dp"
android:text="#string/selectText"
android:textColor="#FFFFFF"
android:textSize="15sp" />
<Spinner
android:id="#+id/spinnerTenants"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:prompt="#string/select_tenant"
android:spinnerMode="dialog"/>
<Spinner
android:id="#+id/spinnerSwitches"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:prompt="#string/select_switch"
android:spinnerMode="dialog"/>
<Spinner
android:id="#+id/spinnerVQs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:prompt="#string/select_vq"
android:spinnerMode="dialog"/>
<ImageButton
android:id="#+id/btnPlus"
android:layout_width="wrap_content"
android:layout_height="0dp"
android:layout_gravity="right"
android:layout_weight="2"
android:background="#00000000"
android:onClick="continueToStats"
android:scaleType="fitEnd"
android:src="#drawable/conf_right" />
Images
I solved it, the thing you need to do is establish a height por each one of the linear layout containing the spinners, for example 60p, and establishing for each spinner a height smaller than the linear layout, for example 50dp

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

Custom layout for Spinner item

I have a spinner within alert dialog. I wanted to reduce padding between spinner items and hence I implemented following:
spinner_row.xml
<?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="30dp"
android:background="#fff" >
<TextView
android:id="#+id/tvCust"
android:layout_width="200dp"
android:layout_height="30dp"
android:gravity="left|center_vertical"
android:textColor="#000"
android:textSize="15sp" />
<RadioButton
android:layout_width="wrap_content"
android:layout_height="30dp"
android:layout_alignParentRight="true" />
</RelativeLayout>
Activity code contains following:
spinner= (Spinner) dialog.findViewById(R.id.spinner);
String arr[] = { "1", "2", "3" };
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
CameraActivity.this, R.layout.spinner_row, R.id.tvCust,arr);
spinner.setAdapter(adapter);
Now as you can see in below screenshot, radio button is getting displayed on spinner which is actually a part of spinner_row.xml. Note that textview width is 200dp while spinner is only 130dp long, so that radio button should not have been displayed on spinner. How can I remove it?
Also, when I click any of the spinner item, spinner pop-up doesn't get disappeared as expected.(note all 3 check-boxes are checked in spinner items list). setOnItemSelectedListener is not getting called on item click.
Any help appreciated.
Edit 1
As per farrukh's suggestion, I tried his code and following is the result.
I have this
and this
with these code of xml
xml for adapter named spinadapt.xml
<?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="30dp"
android:background="#fff" >
<TextView
android:id="#+id/tvCust"
android:layout_width="wrap_content"
android:layout_height="30dp"
android:layout_toLeftOf="#+id/radioButton1"
android:gravity="left|center_vertical"
android:textColor="#000"
android:textSize="15sp" />
<RadioButton
android:layout_width="wrap_content"
android:layout_height="30dp"
android:layout_alignParentRight="true" />
</RelativeLayout>
and main layout named activity_main.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">
<TextView
android:id="#+id/spinner1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:hint="Select item"
android:background="#drawable/spin"/>
</RelativeLayout>
and java code is class named MainActivity.java
public class MainActivity extends Activity
{
Spinner sp;
TextView tv;
String[] counting={"One","Two","Three","Four"};
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sp=new Spinner(this);
tv=(TextView)findViewById(R.id.spinner1);
tv.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
sp.performClick();
}
});
sp.setAdapter(new Adapter(MainActivity.this, counting));
sp.setOnItemSelectedListener(new OnItemSelectedListener()
{
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3)
{
tv.setText(counting[arg2]);
}
#Override
public void onNothingSelected(AdapterView<?> arg0)
{
}
});
}
}
and adapter class named Adapter.java
public class Adapter extends BaseAdapter
{
LayoutInflater inflator;
String[] mCounting;
public Adapter( Context context ,String[] counting)
{
inflator = LayoutInflater.from(context);
mCounting=counting;
}
#Override
public int getCount()
{
return mCounting.length;
}
#Override
public Object getItem(int position)
{
return null;
}
#Override
public long getItemId(int position)
{
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
convertView = inflator.inflate(R.layout.spinadapt, null);
TextView tv = (TextView) convertView.findViewById(R.id.tvCust);
tv.setText(Integer.toString(position));
return convertView;
}
}
this is working perfect
hope this will help

Why Custom Control is not visible in activity_main.xml

This is the new code, It doesn't throw exceptions, but I can't see my custom control "Second". This is the new code:
activity_main.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/layoutRoot"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<LinearLayout
android:id="#+id/L1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical" >
<Button
android:id="#+id/addButton"
android:layout_width="74dp"
android:layout_height="wrap_content"
android:text="Add" />
<EditText
android:id="#+id/newEditText"
android:layout_width="174dp"
android:layout_height="wrap_content"
android:layout_weight="3.24"
android:ems="10"
android:inputType="text" />
</LinearLayout>
<LinearLayout
android:id="#+id/List"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
</LinearLayout>
</LinearLayout>
This is the custom control: second.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/secodView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<Button
android:id="#+id/expandButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="0.44"
android:text = "Expand"/>
<TextView
android:id="#+id/txtView"
android:layout_width="253dp"
android:layout_height="wrap_content"
android:layout_weight="0.56"
android:ems="10"
android:text = "LOL"/>
</LinearLayout>
<RadioGroup
android:id="#+id/ratingRadioGroup"
android:layout_width="321dp"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<RadioButton
android:id="#+id/likeButton"
android:layout_width="145dp"
android:layout_height="wrap_content"
android:checked="true"
android:text="Like" />
<RadioButton
android:id="#+id/dislikeButton"
android:layout_width="147dp"
android:layout_height="wrap_content"
android:text="Dislike" />
</RadioGroup>
</LinearLayout>
Second.java class:
public class Second extends ViewGroup
{
private Button mExpandButton;
private RadioButton mLikeButton;
private RadioButton mDislikeButton;
private TextView mText;
private RadioGroup mLikeGroup;
private ViewGroup vGroup;
OnClickListener myClickListener = new OnClickListener()
{
#Override
public void onClick(View v)
{
String s= mExpandButton.getText().toString();
if (s.equals("One Click"))
mExpandButton.setText("Other Click");
else
mExpandButton.setText("One Click");
}
};
OnCheckedChangeListener myCkeckListener = new OnCheckedChangeListener()
{
#Override
public void onCheckedChanged(RadioGroup group, int checkedId)
{
if (mLikeButton.isChecked())
mText.setText("I Like it");
if (mDislikeButton.isChecked())
mText.setText("I Don't Like it");
}
};
public Second(Context context)
{
super(context);
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = LayoutInflater.from(context).inflate(R.layout.second, this, true);
mText = (TextView)this.findViewById(R.id.txtView);
mExpandButton = (Button) this.findViewById(R.id.expandButton);
mLikeGroup = (RadioGroup)this.findViewById(R.id.ratingRadioGroup);
mExpandButton.setOnClickListener(myClickListener);
mLikeGroup.setOnCheckedChangeListener(myCkeckListener);
//inflater.inflate(R.layout.second, null);
}
#Override
protected void onLayout(boolean arg0, int arg1, int arg2, int arg3, int arg4)
{
// TODO Auto-generated method stub
}
}
ActivityMain.java class, where the activity gets started:
public class MainActivity extends Activity
{
protected LinearLayout mList;
protected EditText mEditText;
protected Button mButton;
Second[] sec;
boolean unavez;
OnClickListener myClickListener = new OnClickListener()
{
#Override
public void onClick(View v)
{
}
};
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mList = (LinearLayout)findViewById(R.id.List);
mEditText = (EditText)findViewById(R.id.newEditText);
mButton = (Button)findViewById(R.id.addButton);
sec = new Second[4];
unavez = true;
for (int i=0; i<4; i++)
sec[i]= new Second(this);
}
#Override
protected void onStart()
{
super.onStart();
}
#Override protected void onResume()
{
super.onResume();
if (!unavez)
return;
for (int i=0; i<4; i++)
{
mList.addView(sec[i]);
//setContentView(sec[i]);
}
unavez = false;
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
When running, I can see the Button and the EditText in activity_main.xml, but I can't see my custom control in second.xml. If I use the line setContentView(sec[i]) instead of mList.addView(sec[i]) in onResume(), it gets worse: the EditText and the Button in activity_main.xml aren't visible and I get a blank layout.
How can I add my custom control to activity_main.xml and make it visible to user?
You elected to have Second inherit directly from ViewGroup. Since you did that, Second needs to be a real ViewGroup, with a real onLayout() implementation and everything else that goes along with being a ViewGroup. Do not just randomly override methods with do-nothing implementations, then complain when the do-nothing implementations do nothing.
Creating "custom controls" is a relatively advanced topic in Android. Newcomers to Android should focus on other solutions to whatever problem they think a "custom control" will somehow solve.

Categories

Resources