Why Custom Control is not visible in activity_main.xml - android

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.

Related

Android: Exit full screen and return to main activity

Main activity contains a spinner and a button. MainActivity.java code is as follows.
public class MainActivity extends AppCompatActivity implements LoadNew.VCallback {
public Spinner dropdown;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dropdown = (Spinner) findViewById(R.id.spinner1);
//Create a list of items for the spinner.
String[] items = new String[]{"select topic", "topic1", "topic2"};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, items);
dropdown.setAdapter(adapter);
dropdown.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
// TODO Auto-generated method stub
String sp1 = String.valueOf(dropdown.getSelectedItem());
if (sp1.contentEquals("select topic")) {
loadFun("");
}
if (sp1.contentEquals("topic1")) {
loadFun("topic1");
}
if (sp1.contentEquals("topic2")) {
loadFun("topic2");
}
}
#Override
public void onNothingSelected(AdapterView<?> parentView){
// TODO Auto-generated method stub
}
});
Button x = (Button) findViewById(R.id.full_screen);
x.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
loadFun("topic2", 0);
}
});
}
public void loadFun(String topicName, int i) {
LoadNew st = new LoadNew(this);
st.display(topicName, i);
}
}
The xml layout for main activity is as follows (activity_main.xml).
<?xml version="1.0" encoding="utf-8"?>
<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:orientation="vertical">
<LinearLayout
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" >
<Spinner
android:id="#+id/spinner1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#android:drawable/btn_dropdown"
android:spinnerMode="dropdown" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<Button
android:id="#+id/full_screen"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Full Screen"
style="?android:attr/borderlessButtonStyle"/>
</LinearLayout>
<LinearLayout
android:id="#+id/full_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
</LinearLayout>
</LinearLayout>
</RelativeLayout>
There is another java class LoadNew.java as follows.
public class LoadNew {
public interface VCallback {
//To access methods of MainActivity class
}
public Activity activity;
public LoadNew(Activity _activity) {
this.activity = _activity;
VCallback callerActivity = (VCallback) activity;
}
//Display PDF
public void display(String topicName, int i) {
LinearLayout fullScreen = (LinearLayout) this.activity.findViewById(R.id.full_view);
fullScreen.removeAllViews();//Clear field
LayoutInflater inflater = (LayoutInflater) this.activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.activity_load, null);
if(i ==0) {
this.activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
this.activity.setContentView(view);
}
TextView tv= (TextView) this.activity.findViewById(R.id.tv1);
tv.setText(topicName);
tv.setTextSize(100);
}
}
The activity_load.xml file is as follows.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout> xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="#+id/tv1"
android:layout_below="#+id/bar"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</RelativeLayout>
When an item is selected in the spinner, the corresponding text is displayed in the textview. Upon pressing the button, the textview appears in full screen mode.
Now I want to return to the previous view (by pressing back button or by single tab on screen), i.e., the view before the button was clicked. How can I achieve this? Thanks in advance for the patience and the help.
Simplest would be to have the spinner and the non-fullscreen TextView on one activity and open a second activity with the fullscreen mode on button click.

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.

listview items not showing up in 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();

Android - Adding a button causes a custom listener to not work

I added a button on list_item.xml and my setOnDataSelectionListener(OnDataSelectionListener listener) doesn't seem to work. All I did was add a button to the LinearLayout, and the listener stopped working. Is there something that needs to be done after adding the button?
list_item.xml:
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:clickable="true"
>
<ImageView
android:id="#+id/iconItem"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="8dp"
android:layout_gravity="center_vertical"
/>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_alignParentLeft="true"
>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="5dp"
>
<TextView
android:id="#+id/dataItem01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#ff888888"
android:textSize="12dp"
android:textStyle="bold"
/>
<TextView
android:id="#+id/dataItem02"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:textColor="#ccf88107"
android:textSize="10dp"
android:textStyle="bold"
android:paddingRight="4dp"
android:clickable="true"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Button"
android:id="#+id/button" />
</RelativeLayout>
<TextView
android:id="#+id/dataItem03"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#191775"
android:textSize="12dp"
android:padding="4dp"
/>
</LinearLayout>
</LinearLayout>
MainActivity:
statusList = (StatusListView) findViewById(R.id.statusList);
statusAdapter = new StatusListAdapter(this, mHandler);
statusList.setAdapter(statusAdapter);
statusList.setOnDataSelectionListener(new OnDataSelectionListener() {
#Override
public void onDataSelected(AdapterView parent, View v, int position, long id) {
Status curItem = (Status) statusAdapter.getItem(position);
String curText = curItem.getText();
Log.d(TAG, "display curtext"); // no log displayed
Toast.makeText(getApplicationContext(), curText, Toast.LENGTH_LONG).show(); // obviously no toast message
}
});
LayoutInflater inflater = this.getLayoutInflater();
LinearLayout list_item = (LinearLayout)inflater.inflate(R.layout.list_item, null);
Button deleteBtn = (Button)list_item.findViewById(R.id.deleteBtn);
deleteBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "delete button clicked");
statusList.setOnDataSelectionListener(new OnDataSelectionListener() {
#Override
public void onDataSelected(AdapterView parent, View v, int position, long id) {
Log.d(TAG, "delete button clicked inside onDataselected");
DeleteStatusThread thread = new MainActivity.DeleteStatusThread(id);
thread.start();
}
});
StatusListView:
public class StatusListView extends ListView {
private OnDataSelectionListener selectionListener;
public StatusListView(Context context) {
super(context);
init();
}
public StatusListView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public void init() {
setOnItemClickListener(new OnItemClickAdapter());
}
class OnItemClickAdapter implements OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (selectionListener == null) {
return;
}
selectionListener.onDataSelected(parent, view, position, id);
}
}
public void setOnDataSelectionListener(OnDataSelectionListener listener) {
selectionListener = listener;
}
public void setAdapter(BaseAdapter adapter) {
super.setAdapter(adapter);
}
public BaseAdapter getAdapter() {
return (BaseAdapter) super.getAdapter();
}
}
If any row item of list contains focusable or clickable view then OnItemClickListener won't work.
The row item must have a param like android:descendantFocusability="blocksDescendants"
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:baselineAligned="false"
android:descendantFocusability="blocksDescendants"
android:gravity="center_vertical" >
// your other widgets here
</LinearLayout>
set any focusable or clickable view in this item with:
android:clickable="false"
android:focusable="false"
android:focusableInTouchMode="false"
If you added the button to list_item.xml you wouldn't initialize the button there because MainActivity as I assume it is not MainActivity's layout file. Instead you should inflate the list_item.xml layout in your MainActivity with a LayoutInflater. Also, I don't see where you initialize your button or declare it in MainActivity but don't forget when doing so it is
Button buttonExample = (Button)findViewById(R.id.btn_id_from_xml);
Then you can use an onClickListener
buttonExample.setOnClickListener(this);
I usually make one onClickListener method with a switch case that changes what happens based on the id of whichever button was clicked that called onClickListener. Good Luck!
set android:focusable="false" to your button in the list_item.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

Categories

Resources