Get Id from Linear Layout Dynamically on click Android - java

I have 4 LinearLayout in my activity i want to get the id of clicked layout how can i get it ??![enter image description here][1]
Url of view image: http://postimg.org/image/uq4hnmlkn/
LinearLayout lt = new LinearLayout(null) ;
lt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), String.valueOf(v.getId()),
Toast.LENGTH_LONG).show();
}
});

Try this way:
1. Xml File (activity_main.xml)
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/lnrMain"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center"/>
2. Java File (MainActivity.java)
public class MainActivity extends Activity {
private LinearLayout lnrMain;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lnrMain = (LinearLayout) findViewById(R.id.lnrMain);
for (int i=1;i<5;i++){
LinearLayout layout = new LinearLayout(this);
layout.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
layout.setId(i);
TextView textView = new TextView(this);
textView.setText("Linear Layout "+i);
textView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT));
layout.addView(textView);
layout.setTag(i);
layout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(MainActivity.this,"Linear Layout "+view.getTag()+" Is Clicked...",Toast.LENGTH_SHORT).show();
}
});
lnrMain.addView(layout);
}
}
}

Related

Seekbar is null, even though it exists

My goal is to access a seekbar. I tried many things, even pulling the Seekbar seekingbar before the override, but I get always the null toast. R.layout.firstLayout, R.layout.secondLayout, R.id.seekingbar, they all exist.
This is my abbreviated code
public class MainActivity extends AppCompatActivity {
SeekBar seekingbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
seekingbar = (SeekBar) findViewById(R.id.seekingbar);
LayoutInflater inflater = getLayoutInflater();
final View firstLayout = inflater.inflate(R.layout.firstLayout, null);
final View secondLayout = inflater.inflate(R.layout.secondLayout, null);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
AlertDialog dialog = new AlertDialog.Builder(MainActivity.this)
.setPositiveButton("Forward", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
AlertDialog dialog2 = new AlertDialog.Builder(MainActivity.this)
.setView(secondLayout)
.setPositiveButton("Okay", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
if (seekingbar == null)
{
Toast.makeText(MainActivity.this,"Null",Toast.LENGTH_LONG).show();
}
}
}).create();
dialog2.show();
}
}).create();
dialog.show();
}
});
}
}
firstLayout.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:id="#+id/seekbarll"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="10dp"
tools:context=".MainActivity">
<SeekBar
android:id="#+id/seekingbar"
style="#style/Widget.AppCompat.SeekBar.Discrete"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:max="10"
android:min="0"
android:progress="3" />
</LinearLayout>
Try to find the seekBar in the firstLayout after declaring it:
"firstLayout.findViewById(R.id.seekbar)"

How to call android:onClick on xml button under another xml listview using fragment?

I tried this method and inflate home.xml in my HomeFragment.java:
public View onCreateView(#NonNull LayoutInflater inflater,ViewGroup container, Bundle savedInstanceState) {
root = inflater.inflate(R.layout.home, container, false);
return root;
}
public void OnClickOnTransit(View v){
final Button n = (Button) v;
final String id = n.getTag().toString();
AlertDialog.Builder builderSingle = new AlertDialog.Builder(getContext());
final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(getContext(), android.R.layout.simple_list_item_1);
arrayAdapter.add("Tag as On Transit");
arrayAdapter.add("Cancel");
builderSingle.setAdapter(arrayAdapter, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String strOption = arrayAdapter.getItem(which);
if(strOption.equalsIgnoreCase("Tag as On Transit"))
{
Tag_as_on_transit(id);
}
else if(strOption.equalsIgnoreCase("Cancel"))
{
//confirmViewLeveling(emp_tag[1],emp_name.getText().toString());
}
else
{
}
}
});
builderSingle.show();
}
Here is my home.xml where i put my listview.
<ListView
android:id="#+id/lv_customer"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
And this is my nested_listview.xml where my button was placed.
<Button
android:id="#+id/btn_ontransit"
android:layout_width="40dip"
android:layout_height="40dip"
android:background = "#drawable/ic_local_shipping_orange_24dp"
android:textColor="#ff4500"
android:textStyle="bold"
android:text=""
android:textSize="25sp"
android:onClick="OnClickOnTransit"/>
What i want is to call OnClickOnTransit from nested_listview.xml. Thanks in advance!
In that case your parentActivity must have this method
public void OnClickOnTransit(View v){
}
However if you don't want that, You can implement like this in your fragment's onViewcreated method.
Button btn_conferma = (Button) view.findViewById(R.id.btn_conferma);
btn_conferma.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
// do something
}
});

Shared preferences working only for the first app restart. On restarting the app second time card view titles are not retained

I have created an app which adds cards and a title is set on each card after taking a name input from user. In order to retain the cards and the title during app restart I am using sharedpreferences and saving the individual card titles in an array. The issue is after first app restart the card titles are retained but on further app restart the card titles are not retained. Although the number of cards are still retained.
public class MainActivity extends AppCompatActivity {
private CardView cardview;
private CardView cardview2;
private LinearLayout.LayoutParams layoutparams1;
private LinearLayout layout;
public SharedPreferences mSettings;
int mCount;
int i=0,j=0;
public TextView tv1;
public TextView tv4;
public TextView tv3;
String name;
String names[] = new String[10];
String key[] = {"A","B","C","D","F","G","H"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mCount=0;
Button b1 = findViewById(R.id.button);
layout=findViewById(R.id.view);
tv1 = findViewById(R.id.textView);
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
names[mCount] = tv1.getText().toString().trim();
mCount++;
saveName();
}
});
}
private void saveName() //Cardview-1 function to
{
cardview = new CardView(getApplicationContext());
layoutparams1 = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
layoutparams1.setMargins(18, 30, 18, 0);
cardview.setLayoutParams(layoutparams1);
cardview.setCardBackgroundColor(Color.WHITE);
cardview.setMinimumHeight(400);
tv3 = new TextView(getApplicationContext());
tv3.setText(tv1.getText().toString().trim());
cardview.setRadius(30);
cardview.addView(tv3);
layout.addView(cardview);
}
private void saveName2() //Cardview 2 function
{
cardview2 = new CardView(getApplicationContext());
layoutparams1 = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
layoutparams1.setMargins(18, 30, 18, 0);
cardview2.setLayoutParams(layoutparams1);
cardview2.setCardBackgroundColor(Color.WHITE);
cardview2.setMinimumHeight(400);
tv4 = new TextView(getApplicationContext());
mSettings = getSharedPreferences("APP_PREFERENCES", Context.MODE_PRIVATE);
name = mSettings.getString(key[j],"");
tv4.setText(name);
j++;
cardview2.setRadius(30);
cardview2.addView(tv4);
layout.addView(cardview2);
}
#Override
public void onPause() {
super.onPause();
mSettings = getSharedPreferences("APP_PREFERENCES", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = mSettings.edit();
editor.putInt("COUNT_CARDS", mCount);
for(int i=0; i<mCount; i++)
editor.putString(key[i],names[i]);
editor.commit();
}
#Override
public void onResume() {
super.onResume();
mSettings = getSharedPreferences("APP_PREFERENCES", Context.MODE_PRIVATE);
if(mSettings.contains("COUNT_CARDS"))
{
mCount = mSettings.getInt("COUNT_CARDS", 0);
for (int i=0; i<mCount; i++)
saveName2();
}
}
}
XML File
<?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:id="#+id/layout"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Save"
android:id="#+id/button"
android:layout_centerHorizontal="true"
android:layout_marginTop="50dp" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/view"
android:orientation="vertical"
android:layout_marginTop="200dp"
android:background="#color/cardview_dark_background">
</LinearLayout>
<EditText
android:id="#+id/textView"
android:layout_width="match_parent"
android:layout_height="40dp" />
</RelativeLayout>
There is no need to store every card in onPause() method. We will only write new card in sharedPref as prev cards are already presen in sharedPref. So when you are trying to save the prev cards in the loop, there is a problem.( writing blank value).
public class MainActivity extends AppCompatActivity {
private CardView cardview;
private CardView cardview2;
private LinearLayout.LayoutParams layoutparams1;
private LinearLayout layout;
public SharedPreferences mSettings;
int mCount;
int i=0,j=0;
public TextView tv1;
public TextView tv4;
public TextView tv3;
String name;
String names[] = new String[10];
String key[] = {"A","B","C","D","F","G","H"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mCount=0;
Button b1 = findViewById(R.id.button);
layout=findViewById(R.id.view);
tv1 = findViewById(R.id.textView);
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
names[mCount] = tv1.getText().toString().trim();
mCount++;
saveName();
}
});
}
private void saveName() //Cardview-1 function to
{
cardview = new CardView(getApplicationContext());
layoutparams1 = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
layoutparams1.setMargins(18, 30, 18, 0);
cardview.setLayoutParams(layoutparams1);
cardview.setCardBackgroundColor(Color.WHITE);
cardview.setMinimumHeight(400);
tv3 = new TextView(getApplicationContext());
tv3.setText(tv1.getText().toString().trim());
cardview.setRadius(30);
cardview.addView(tv3);
layout.addView(cardview);
saveInPref();
}
private void saveInPref() {
mSettings = getSharedPreferences("APP_PREFERENCES", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = mSettings.edit();
editor.putInt("COUNT_CARDS", mCount);
editor.putString(key[mCount-1],names[mCount-1]);
editor.apply();
}
private void saveName2() //Cardview 2 function
{
cardview2 = new CardView(getApplicationContext());
layoutparams1 = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
layoutparams1.setMargins(18, 30, 18, 0);
cardview2.setLayoutParams(layoutparams1);
cardview2.setCardBackgroundColor(Color.WHITE);
cardview2.setMinimumHeight(400);
tv4 = new TextView(getApplicationContext());
mSettings = getSharedPreferences("APP_PREFERENCES", Context.MODE_PRIVATE);
name = mSettings.getString(key[j],"");
tv4.setText(name);
j++;
cardview2.setRadius(30);
cardview2.addView(tv4);
layout.addView(cardview2);
}
#Override
public void onResume() {
super.onResume();
mSettings = getSharedPreferences("APP_PREFERENCES", Context.MODE_PRIVATE);
if(mSettings.contains("COUNT_CARDS"))
{
mCount = mSettings.getInt("COUNT_CARDS", 0);
for (int i=0; i<mCount; i++)
saveName2();
}
}
}
So when you click on the SAVE button then only you can save card in SharedPref. This will save in unnecessary write operation on sharedPref.

how to dynamically change the position of buttons

I have a MainActivity initially empty with an action bar. Clicking on the "plus" in the action bar,I open a DialogFragment with an EditText and two buttons, "cancel" and "continue". I can not post a picture because I do not have enough reputation, but when I click on "continue" I create two buttons; one positioned at the top right of the layout of MainActivity and the other, just below the previous one, on the left. What I would like is that every time I click on "continue", I can create two buttons positioned according to the same pattern that I explained earlier.
This is the code I've written but it does not work as I would like.
MainActivity
public class MainActivity extends FragmentActivity implements IProjectDialFrag {
private ProjectDialogFragment projectDialFrag = new ProjectDialogFragment();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id) {
case R.id.action_settings:
//TODO
return true;
case R.id.filters:
Intent intent1 = new Intent(MainActivity.this, FiltersActivity.class);
startActivity(intent1);
return true;
case R.id.action_new:
return true;
case R.id.add_button:
Intent intent2 = new Intent(MainActivity.this, ButtonsActivity.class);
startActivity(intent2);
return true;
case R.id.add_project:
projectDialFrag.show(getFragmentManager(), "projectDialog");
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onDialogNegativeClick(DialogFragment dialog) {
return;
}
#Override
public void onDialogPositiveClick(DialogFragment dialog) {
EditText editText = (EditText) dialog.getDialog().findViewById(R.id.project_name);
String projectName = editText.getText().toString();
Button projectButton = new Button(this);
projectButton.setText(projectName);
ImageButton playButton = new ImageButton(this);
playButton.setImageResource(R.drawable.ic_action_play_over_video);
LinearLayout linearLayout = (LinearLayout) findViewById(R.id.button_row);
linearLayout.addView(projectButton);
linearLayout.addView(playButton);
}
}
The Interface
public interface IProjectDialFrag {
public void onDialogPositiveClick(DialogFragment dialog);
public void onDialogNegativeClick(DialogFragment dialog);
}
And the DialogFragment
public class ProjectDialogFragment extends DialogFragment {
private IProjectDialFrag iProjDialFrag;
#SuppressLint("InflateParams")
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder createProjectAlert = new AlertDialog.Builder(getActivity());
createProjectAlert.setTitle("Create Project");
LayoutInflater inflater = getActivity().getLayoutInflater();
createProjectAlert.setView(inflater.inflate(R.layout.project_dialog_fragment, null))
.setPositiveButton(R.string.conti_nue, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
iProjDialFrag.onDialogPositiveClick(ProjectDialogFragment.this);
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
iProjDialFrag.onDialogNegativeClick(ProjectDialogFragment.this);
}
});
return createProjectAlert.create();
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
iProjDialFrag = (IProjectDialFrag) activity;
}
}
The layout of MainActivity
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/main_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<LinearLayout
android:id="#+id/button_row"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" >
</LinearLayout>
</RelativeLayout>
If you need a screenshot, please give me a point reputation and I'll place it immediately. Than you
Thank you again. Here is my screenshot:
This is the result I'd like to have:
For each Button I have to be able to add more "play".
But see your layout.
Your linear layout is "wrap_conent" on the width.
Also your linear layout is glued to the right side of parent.
So that is exactly what you will be getting... all the linear layout content glued to the right side and taking exaclty size of it's content... Well Button. You are getting what you told Android to get.
If you want to get what you drawn, then 1st your linear layout for button shoul be match_parent in widht, and you can set it's gravity to left for play buttons and to right for CIAO and LUCA buttons...
<LinearLayout
...
android:layout_width="wrap_content"
... >
in MainActivity layout should change to
<LinearLayout
...
android:layout_width="fill_parent"
... >
and add these lines
LayoutParams lp = new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT) <---
lp.gravity = Gravity.RIGHT; <---
Button projectButton = new Button(this);
projectButton.setText(projectName);
projectButton.setLayoutParams(lp); <---
lp.gravity = Gravity.LEFT; <---
ImageButton playButton = new ImageButton(this);
playButton.setImageResource(R.drawable.ic_action_play_over_video);
playButton.setLayoutParams(lp); <---
#udiboy1209
I simply refactor your code as I show below:
#Override
public void onDialogPositiveClick(DialogFragment dialog) {
EditText editText = (EditText) dialog.getDialog().findViewById(R.id.project_name);
String projectName = editText.getText().toString();
LinearLayout.LayoutParams lp1 = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
lp1.gravity = Gravity.END;
Button projectButton = new Button(this);
projectButton.setText(projectName);
projectButton.setLayoutParams(lp1);
LinearLayout.LayoutParams lp2 = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
lp2.gravity = Gravity.START;
Button playButton = new Button(this);
playButton.setBackgroundResource(R.drawable.play_button_green);
playButton.setLayoutParams(lp2);
LinearLayout linearLayout = (LinearLayout) findViewById(R.id.button_row);
linearLayout.addView(projectButton);
linearLayout.addView(playButton);
}

Can't make the button refer to another activity in android

I want the button to show some texts when it is clicked. When we click the 'formula' button, a new blank page should open up in the phone showing the layout of the activity.. Here are my codes
MainActivity.java
public class MainActivity extends Activity {
public final static String EXTRA_MESSAGE = "";
// ....
public void sendMessage(View view) {
Intent intent = new Intent(MainActivity.this, FormulaActivity.class);
EditText editText = (EditText) findViewById(R.id.edit);
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
// Do something in response to button
startActivity(intent);
FormulaActivity.java
public class FormulaActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
TextView textView = new TextView(this);
textView.setTextSize(40);
textView.setText(message);
// Set the text view as the activity layout
setContentView(textView);
}
MainActivity.xml (button coding)
<Button
android:id="#+id/formula"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="sendMessage"
android:text="Formula" />
You just need to intialize the Button and EditText inside your MainActivity.java
XML Layout File
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<EditText
android:id="#+id/edit"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="top"
/>
<Button
android:id="#+id/formula"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Formula"
android:gravity="bottom"
/>
public class MainActivity extends Activity
{
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
Button F=(Button)findViewById(R.id.formula);
EditText editText = (EditText) findViewById(R.id.edit);
F.setOnClickListener(new View.onClickListener()
{
public void onClick()
{
sendMessage();
}
}
}
public void sendMessage()
{
String message = editText.getText().toString();
Intent intent = new Intent(MainActivity.this, FormulaActivity.class);
intent.putExtra("EXTRA_MESSAGE", message);
startActivity(intent);
}
}
public class FormulaActivity extends Activity
{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
String message = intent.getStringExtra("EXTRA_MESSAGE");
TextView textView = new TextView(this);
textView.setTextSize(40);
textView.setText(message);
// Set the text view as the activity layout
setContentView(textView);
}
Your public final static String EXTRA_MESSAGE = ""; is empty string. Try changing it to any valued string.
Hope this will help you.

Categories