Clickable effect for ImageButtons - android

How to give click-able effect for the buttons whose background is an image ? Though it functions correctly but its just looking like an image. Any help would be appreciated.

You have to create different images and put them in a selector. Take a look at this tutorial for further details:
Custom Button Backgrounds Using A Selector XML Layout

This is what I did for my dice game.
In your XML you can do:
<?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" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/hello" />
<ImageButton
android:id = "#+id/dice1"
android:src = "#drawable/red_1_dice"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:layout_marginTop = "60px"
android:layout_marginLeft = "30px" />
<ImageButton
android:id = "#+id/dice2"
android:src = "#drawable/red_2_dice"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:layout_marginLeft = "250px"
android:layout_marginTop = "-130px"/>
<ImageButton
android:id = "#+id/dice3"
android:src = "#drawable/red_3_dice"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:layout_marginLeft = "135px"
android:layout_marginTop = "20px" />
In Your MainActivity.Java you can do:
import android.app.Activity;
import android.os.Bundle;
import android.widget.ImageButton;
import android.widget.Button;
import android.widget.Toast;
import android.view.View;
import android.view.View.OnClickListener;
import java.util.Random;
public class Z_veselinovic_yahtzeeActivity extends Activity
{
/** Called when the activity is first created. */
ImageButton button1, button2, button3, button4, button5;
Button start, reroll, hold;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Buttons();
}
public void Buttons()
{
button1 = (ImageButton)findViewById(R.id.dice1);
button2 = (ImageButton)findViewById(R.id.dice2);
button3 = (ImageButton)findViewById(R.id.dice3);
button4 = (ImageButton)findViewById(R.id.dice4);
button5 = (ImageButton)findViewById(R.id.dice5);
start = (Button)findViewById(R.id.Start);
reroll = (Button)findViewById(R.id.Reroll);
hold = (Button)findViewById(R.id.Hold);
reroll.setVisibility(View.GONE);
hold.setVisibility(View.GONE);
start.setOnClickListener(new OnClickListener()
{
public void onClick(View whatever)
{
Toast.makeText(getBaseContext(), start.getText() + " Game", Toast.LENGTH_LONG).show();
Random rand1 = new Random();
Random rand2 = new Random();
Random rand3 = new Random();
Random rand4 = new Random();
Random rand5 = new Random();
int dice_num_1 = rand1.nextInt(6) + 1;
int dice_num_2 = rand2.nextInt(6) + 1;
int dice_num_3 = rand3.nextInt(6) + 1;
int dice_num_4 = rand4.nextInt(6) + 1;
int dice_num_5 = rand5.nextInt(6) + 1;
if(dice_num_1 == 1)
{
button1.setImageResource(R.drawable.red_1_dice);
}
else if(dice_num_1 == 2)
{
button1.setImageResource(R.drawable.red_2_dice);
}
else if(dice_num_1 == 3)
{
button1.setImageResource(R.drawable.red_3_dice);
}
else if(dice_num_1 == 4)
{
button1.setImageResource(R.drawable.red_4_dice);
}
else if(dice_num_1 == 5)
{
button1.setImageResource(R.drawable.red_5_dice);
}
else if(dice_num_1 == 6)
{
button1.setImageResource(R.drawable.red_6_dice);
}
I hope this helps.

This is my simplest solution especially for round button.
android:background="?android:selectableItemBackgroundBorderless"
Or you can also try this
android:background="?android:actionBarItemBackground"

Related

How to set a line break after a set of EditText which have been dynamically created?

I am trying to show few EditText field just like n*n Matrix. I am creating these EditText field dynamically.
Problem is all my EditText field prints in the same line horizontally.
I wanted to know is there anything like "System.out.println();" in Android Studio!
Note: I want this line break in between Views, not in between Text, so \n doesn't work here!
This is my activity_main.xml file,
<?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/mainLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_gravity="center"
tools:context=".MainActivity">
<EditText
android:id="#+id/a"
android:layout_width="80dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginBottom="5dp"
android:gravity="center"
android:inputType="number" />
<Button
android:id="#+id/btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:background="#android:color/holo_purple"
android:text="Click"
android:textColor="#android:color/white" />
<LinearLayout
android:id="#+id/child_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:orientation="horizontal">
<!--EditText Fields going to be here!-->
</LinearLayout>
</LinearLayout>
And Here's my MainActivity.java file
package com.ridi.magicfield;
import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TableLayout;
import android.widget.TableRow;
public class MainActivity extends AppCompatActivity {
private static int a;
private static EditText magicField, ainput;
private static Button btn;
private static LinearLayout child_layout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
child_layout = (LinearLayout) findViewById(R.id.child_layout);
ainput = (EditText) findViewById(R.id.a);
btn = (Button) findViewById(R.id.btn);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
a = Integer.parseInt(ainput.getText().toString());
child_layout.removeAllViews();
createMatrixInputField();
}
});
}
private void createMatrixInputField() {
int p = 1;
for (int t = 1; t <= a; t++) {
for (int i = 1; i <= a; i++) {
magicField = new EditText(MainActivity.this);
magicField.setId((p));
magicField.setHint("et-" + (Integer.toString(p)));
magicField.setGravity(Gravity.CENTER);
child_layout.addView(magicField);
p++;
}
}
}
}
Here's my output screen. I want et-3 and et-4 to go to next line.
Is there anyone who can help please...
Output Screen Image
Use TableLayout instead of LinearLayout for n*n matrix pattern
for (int i = 0; i < noOfRows; i++) {
TableRow row= new TableRow(this);
TableRow.LayoutParams lp = new
TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT
,TableRow.LayoutParams.WRAP_CONTENT);
row.setLayoutParams(lp);
for(int j = 0; j < noOfColumns; j++) {
EditText et = new EditText(this);
//Extra properties goes here...
et.setText("Your text");
row.addView(et,j);
}
tableLayout.addView(row,i);
}

Creating views programmatically

I'm a new android developer and I decided to create a simple test app that has 6 editViews and calculates the average of those numbers inputted.
I am looking to find out how to create the views programmatically when needed instead of wasting resources on having all of the views there OnCreate.
I've been searching around but have been unable find out how to implement it. If someone could help out that would be great.
Thanks!
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
average = (TextView)findViewById(R.id.average);
edit_message = (EditText)findViewById(R.id.edit_message);
editText = (EditText)findViewById(R.id.editText);
editText2 = (EditText)findViewById(R.id.editText2);
editText3 = (EditText)findViewById(R.id.editText3);
editText4 = (EditText)findViewById(R.id.editText4);
editText5 = (EditText)findViewById(R.id.editText5);
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
s1 = edit_message.getText().toString();
s2 = editText.getText().toString();
s3 = editText2.getText().toString();
s4 = editText3.getText().toString();
s5 = editText4.getText().toString();
s6 = editText5.getText().toString();
if(!s1.isEmpty()) {
n1 = Integer.parseInt(s1);
counter++;
}
if(!s2.isEmpty()) {
n2 = Integer.parseInt(s2);
counter++;
}
if(!s3.isEmpty()) {
n3 = Integer.parseInt(s3);
counter++;
}
if(!s4.isEmpty()) {
n4 = Integer.parseInt(s4);
counter++;
}
if(!s5.isEmpty()) {
n5 = Integer.parseInt(s5);
counter++;
}
if(!s6.isEmpty()) {
n6 = Integer.parseInt(s6);
counter++;
}
if(counter>0) {
s1 = String.valueOf((n1 + n2 + n3 + n4 + n5 + n6) / counter);
average.setText(s1);
}
else {
average.setText("0");
}
counter = 0;
}
});
}
Without more details, I'll give you at least a place to start. You can instantiate TextViews programmatically and then add them to your layout.
TextView tv = new TextView(context);
parent.addView(tv);
context should be your Activity or Fragment that this text view will be apart of. The parent should be a ViewGroup in your XML layout that can have multiple children like a vertical LinearLayout. Hopefully this is enough information to guide you to better Google Searching.
EDIT
LinearLayout - Not a list layout, brain fart.
This is a sample just for reference:
The layout file:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.test.MainActivity" >
<ScrollView
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1" >
<LinearLayout
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" />
</ScrollView>
<Button
android:id="#+id/add"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="add" />
<Button
android:id="#+id/del"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="del" />
<Button
android:id="#+id/sum"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="sum" />
</LinearLayout>
This is the activity:
package com.example.test;
import android.app.Activity;
import android.os.Bundle;
import android.text.InputType;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
public class MainActivity extends Activity {
LinearLayout container;
Button add;
Button del;
Button sum;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
container = (LinearLayout) findViewById(R.id.container);
add = (Button) findViewById(R.id.add);
del = (Button) findViewById(R.id.del);
sum = (Button) findViewById(R.id.sum);
add.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
EditText edit = new EditText(MainActivity.this);
LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
edit.setLayoutParams(params);
edit.setInputType(InputType.TYPE_CLASS_NUMBER);
container.addView(edit);
}
});
del.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
int count = container.getChildCount();
if (count > 0)
container.removeViewAt(count - 1);
}
});
sum.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
int count = container.getChildCount();
int sum = 0;
for (int i = 0; i < count; i++) {
EditText edit = (EditText) container.getChildAt(i);
String numStr = edit.getText().toString();
if (numStr == null || !(numStr.length() > 0)) {
sum += 0;
} else {
sum += Integer.parseInt(numStr);
}
}
Log.i("Test", "sum = " + sum + " avg = " + (sum * 1.0f / count));
}
});
}
}

cannot be resolved or is not a field with layout textview and button

I'm getting four errors all with this message: cannot be resolved or is not a field
The errors are in two different .java files
StartScreen.java.text
tv = (TextView) findViewById(R.id.startscreen); (startscreen underlined in red)
Button startButton = (Button) findViewById(R.id.play_game); (play_game underlined in red)
I creaded a textview called startscreen and a button called startButton inside game.xml
PlayGame.java
tv2 = (TextView) findViewById(R.id.game_text); (game_text underlined in red)
Button startButton = (Button) findViewById(R.id.end_game); (end_game underlined in red)
I creaded a textview called game_text and a button called end_game inside game.xml
StartScreen.java
package com.example.startscreenapp;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class StartScreen extends Activity {
private static final int PLAY_GAME = 1010;
private TextView tv;
private int meaningOfLife = 42;
private String userName = "Douglas Adams";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView) findViewById(R.id.startscreen.text);
//Display initial values
tv.setText(userName + ":" + meaningOfLife);
//Set up button listener
Button startButton = (Button) findViewById(R.id.play_game);
startButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
startGame();
}
});
}
#Override
protected void onActivityResult(int requestCode,
int resultCode, Intent data) {
if (requestCode == PLAY_GAME && resultCode == RESULT_OK) {
meaningOfLife = data.getExtras().getInt("returnInt");
userName = data.getExtras().getString("returnStr");
//Show it has changed
tv.setText(userName + ":" + meaningOfLife);
}
super.onActivityResult(requestCode, resultCode, data);
}
private void startGame() {
Intent launchGame = new Intent(this, PlayGame.class);
//passing information to launched activity
launchGame.putExtra("meaningOfLife", meaningOfLife);
launchGame.putExtra("userName", userName);
startActivityForResult(launchGame, PLAY_GAME);
}
}
PlayGame.java
package com.example.startscreenapp;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class PlayGame extends Activity {
private TextView tv2;
int answer;
String author;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.game);
tv2 = (TextView) findViewById(R.id.game_text);
//reading information passed to this activity
//Get the intent that started this activity
Intent i = getIntent();
//returns -1 if not initialized by calling activity
answer = i.getIntExtra("meaningOfLife", -1);
//returns [] if not initialized by calling activity
author = i.getStringExtra("userName");
tv2.setText(author + ":" + answer);
//Change values for an example of return
answer = answer - 41;
author = author + " Jr.";
//Set up button listener
Button startButton = (Button) findViewById(R.id.end_game);
startButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
//Return information to calling activity
Intent i = getIntent();
i.putExtra("returnInt", answer);
i.putExtra("returnStr", author);
setResult(RESULT_OK, i);
finish();
}
});
}}
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"
tools:context="${relativePackage}.${activityClass}" >
<TextView
android:id="#+id/startscreen"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="115dp"
android:layout_marginTop="164dp"
android:text="TextView" />
<Button
android:id="#+id/play_game"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/startscreen"
android:layout_below="#+id/startscreen"
android:layout_marginTop="64dp"
android:text="Button" />
</RelativeLayout>
game.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/game_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView" />
<Button
android:id="#+id/end_game"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button" />
</LinearLayout>
Your textview id on your xml is startscreen
Instead of v = (TextView) findViewById(R.id.startscreen.text); just remove the .text part
in startscreen.java you have tv = (TextView) findViewById(R.id.startscreen.text); and in your activity_main.xml you have android:id="#+id/startscreen".
what you should do :
1-is removing the .text from tv = (TextView) findViewById(R.id.startscreen.text);
2- clean and build you project again. (if this didn't work , close and open eclipse again.
i suggest to use ctrl + space in completing you statement, that would help in reducing error and give suggestion.

show EditText on condition

Right now I have an idea for a project and I would like to know if anyone can help me on the same logic.
As such I need to create or generate a number of EditText according to amount you enter, ie, to select or enter a number such as 5, show me 5 EditText layout for type 5 values​​. They know that the form could accomplish this? Any ideas please?
I guess it must be a way to do it with a loop, but not like carrying this calculation Java to XML. Thank you.
Here is an example of generating EditText items based on the number you enter. You can ignore the scrollview in the layout file I just put it in case someone added a lot of EditText items that would go off the screen.
MainActivity.java
package com.example.test;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;
public class MainActivity extends Activity {
public static final String TAG = MainActivity.class.getSimpleName();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText count = (EditText) findViewById(R.id.count);
final TextView output = (TextView) findViewById(R.id.output);
final Button generate = (Button) findViewById(R.id.generate);
final Button values = (Button) findViewById(R.id.values);
final LinearLayout container = (LinearLayout) findViewById(R.id.container);
generate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int numberOfControlsToGenerate = 0;
try {
numberOfControlsToGenerate = Integer.parseInt(count.getText().toString().trim());
} catch (NumberFormatException e) {
Log.e(TAG, e.getMessage(), e);
}
if (numberOfControlsToGenerate > 0) {
if (container.getChildCount() > 0) {
container.removeAllViews();
}
for (int counter = 0; counter < numberOfControlsToGenerate; counter++) {
addEditText(container);
}
}
}
});
values.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String[] editTextValues = new String[container.getChildCount()];
StringBuilder editTextValuesBuilder = new StringBuilder();
for (int counter = 0; counter < container.getChildCount(); counter++) {
EditText child = (EditText) container.getChildAt(counter);
editTextValues[counter] = child.getText().toString().trim();
editTextValuesBuilder.append(editTextValues[counter]).append("\n");
}
output.setText(editTextValuesBuilder.toString());
}
});
}
private void addEditText(LinearLayout container) {
final LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
EditText editTextToAdd = new EditText(this);
editTextToAdd.setLayoutParams(params);
container.addView(editTextToAdd);
}
}
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_horizontal"
android:orientation="vertical"
android:padding="16dp"
tools:context="${packageName}.${activityClass}" >
<EditText
android:id="#+id/count"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:imeOptions="actionDone"
android:inputType="number"
android:textSize="20sp" />
<Button
android:id="#+id/generate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Go" />
<Button
android:id="#+id/values"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Get Values" />
<TextView
android:id="#+id/output"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent" >
<LinearLayout
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
</LinearLayout>
</ScrollView>
</LinearLayout>

Add and Remove Views in Android Dynamically?

How do I add and remove views such as TextViews from Android app like on the original stock Android contacts screen where you press a small icon on the right side of a field and it adds or deletes a field which consists of a TextView and an editTextView (from what I can see).
Any examples on how to achieve this?
ViewParents in general can't remove views, but ViewGroups can. You need to cast your parent to a ViewGroup (if it is a ViewGroup) to accomplish what you want.
For example:
View namebar = View.findViewById(R.id.namebar);
((ViewGroup) namebar.getParent()).removeView(namebar);
Note that all Layouts are ViewGroups.
I need the exact same feature described in this question. Here is my solution and source code: https://github.com/laoyang/android-dynamic-views. And you can see the video demo in action here: http://www.youtube.com/watch?v=4HeqyG6FDhQ
Layout
Basically you'll two xml layout files:
A horizontal LinearLayout row view with a TextEdit, a Spinner and an ImageButton for deletion.
A vertical LinearLayout container view with just a Add new button.
Control
In the Java code, you'll add and remove row views into the container dynamically, using inflate, addView, removeView, etc. There are some visibility control for better UX in the stock Android app. You need add a TextWatcher for the EditText view in each row: when the text is empty you need to hide the Add new button and the delete button. In my code, I wrote a void inflateEditRow(String) helper function for all the logic.
Other tricks
Set android:animateLayoutChanges="true" in xml to enable animation
Use custom transparent background with pressed selector to make the buttons visually the same as the ones in the stock Android app.
Source code
The Java code of the main activity ( This explains all the logic, but quite a few properties are set in xml layout files, please refer to the Github source for complete solution):
public class MainActivity extends Activity {
// Parent view for all rows and the add button.
private LinearLayout mContainerView;
// The "Add new" button
private Button mAddButton;
// There always should be only one empty row, other empty rows will
// be removed.
private View mExclusiveEmptyView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.row_container);
mContainerView = (LinearLayout) findViewById(R.id.parentView);
mAddButton = (Button) findViewById(R.id.btnAddNewItem);
// Add some examples
inflateEditRow("Xiaochao");
inflateEditRow("Yang");
}
// onClick handler for the "Add new" button;
public void onAddNewClicked(View v) {
// Inflate a new row and hide the button self.
inflateEditRow(null);
v.setVisibility(View.GONE);
}
// onClick handler for the "X" button of each row
public void onDeleteClicked(View v) {
// remove the row by calling the getParent on button
mContainerView.removeView((View) v.getParent());
}
// Helper for inflating a row
private void inflateEditRow(String name) {
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View rowView = inflater.inflate(R.layout.row, null);
final ImageButton deleteButton = (ImageButton) rowView
.findViewById(R.id.buttonDelete);
final EditText editText = (EditText) rowView
.findViewById(R.id.editText);
if (name != null && !name.isEmpty()) {
editText.setText(name);
} else {
mExclusiveEmptyView = rowView;
deleteButton.setVisibility(View.INVISIBLE);
}
// A TextWatcher to control the visibility of the "Add new" button and
// handle the exclusive empty view.
editText.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable s) {
// Some visibility logic control here:
if (s.toString().isEmpty()) {
mAddButton.setVisibility(View.GONE);
deleteButton.setVisibility(View.INVISIBLE);
if (mExclusiveEmptyView != null
&& mExclusiveEmptyView != rowView) {
mContainerView.removeView(mExclusiveEmptyView);
}
mExclusiveEmptyView = rowView;
} else {
if (mExclusiveEmptyView == rowView) {
mExclusiveEmptyView = null;
}
mAddButton.setVisibility(View.VISIBLE);
deleteButton.setVisibility(View.VISIBLE);
}
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
}
});
// Inflate at the end of all rows but before the "Add new" button
mContainerView.addView(rowView, mContainerView.getChildCount() - 1);
}
This is my general way:
View namebar = view.findViewById(R.id.namebar);
ViewGroup parent = (ViewGroup) namebar.getParent();
if (parent != null) {
parent.removeView(namebar);
}
Hi You can try this way by adding relative layout and than add textview in that.
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
(LayoutParams.WRAP_CONTENT), (LayoutParams.WRAP_CONTENT));
RelativeLayout relative = new RelativeLayout(getApplicationContext());
relative.setLayoutParams(lp);
TextView tv = new TextView(getApplicationContext());
tv.setLayoutParams(lp);
EditText edittv = new EditText(getApplicationContext());
edittv.setLayoutParams(lp);
relative.addView(tv);
relative.addView(edittv);
Just use myView.setVisibility(View.GONE); to remove it completely.
But if you want to reserve the occupied space inside its parent use myView.setVisibility(View.INVISIBLE);
Kotlin Extension Solution
Add removeSelf to directly call on a view. If attached to a parent, it will be removed. This makes your code more declarative, and thus readable.
myView.removeSelf()
fun View?.removeSelf() {
this ?: return
val parent = parent as? ViewGroup ?: return
parent.removeView(this)
}
Here are 3 options for how to programmatically add a view to a ViewGroup.
// Built-in
myViewGroup.addView(myView)
// Reverse addition
myView.addTo(myViewGroup)
fun View?.addTo(parent: ViewGroup?) {
this ?: return
parent ?: return
parent.addView(this)
}
// Null-safe extension
fun ViewGroup?.addView(view: View?) {
this ?: return
view ?: return
addView(view)
}
ViewGroup class provides API for child views management in run-time, allowing to add/remove views as well.
Some other links on the subject:
Android, add new view without XML Layout
Android Runtime Layout Tutorial
http://developer.android.com/reference/android/view/View.html
http://developer.android.com/reference/android/widget/LinearLayout.html
For Adding the Button
LinearLayout dynamicview = (LinearLayout)findViewById(R.id.buttonlayout);
LinearLayout.LayoutParams lprams = new LinearLayout.LayoutParams( LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
Button btn = new Button(this);
btn.setId(count);
final int id_ = btn.getId();
btn.setText("Capture Image" + id_);
btn.setTextColor(Color.WHITE);
btn.setBackgroundColor(Color.rgb(70, 80, 90));
dynamicview.addView(btn, lprams);
btn = ((Button) findViewById(id_));
btn.setOnClickListener(this);
For removing the button
ViewGroup layout = (ViewGroup) findViewById(R.id.buttonlayout);
View command = layout.findViewById(count);
layout.removeView(command);
Hi First write the Activity class. The following class have a Name of category and small add button. When you press on add (+) button it adds the new row which contains an EditText and an ImageButton which performs the delete of the row.
package com.blmsr.manager;
import android.app.Activity;
import android.app.ListActivity;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import com.blmsr.manager.R;
import com.blmsr.manager.dao.CategoryService;
import com.blmsr.manager.models.CategoryModel;
import com.blmsr.manager.service.DatabaseService;
public class CategoryEditorActivity extends Activity {
private final String CLASSNAME = "CategoryEditorActivity";
LinearLayout itsLinearLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_category_editor);
itsLinearLayout = (LinearLayout)findViewById(R.id.linearLayout2);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_category_editor, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
switch (item.getItemId()) {
case R.id.action_delete:
deleteCategory();
return true;
case R.id.action_save:
saveCategory();
return true;
case R.id.action_settings:
return true;
default:
return super.onOptionsItemSelected(item);
}
}
/**
* Adds a new row which contains the EditText and a delete button.
* #param theView
*/
public void addField(View theView)
{
itsLinearLayout.addView(tableLayout(), itsLinearLayout.getChildCount()-1);
}
// Using a TableLayout as it provides you with a neat ordering structure
private TableLayout tableLayout() {
TableLayout tableLayout = new TableLayout(this);
tableLayout.addView(createRowView());
return tableLayout;
}
private TableRow createRowView() {
TableRow tableRow = new TableRow(this);
tableRow.setPadding(0, 10, 0, 0);
EditText editText = new EditText(this);
editText.setWidth(600);
editText.requestFocus();
tableRow.addView(editText);
ImageButton btnGreen = new ImageButton(this);
btnGreen.setImageResource(R.drawable.ic_delete);
btnGreen.setBackgroundColor(Color.TRANSPARENT);
btnGreen.setOnClickListener(anImageButtonListener);
tableRow.addView(btnGreen);
return tableRow;
}
/**
* Delete the row when clicked on the remove button.
*/
private View.OnClickListener anImageButtonListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
TableRow anTableRow = (TableRow)v.getParent();
TableLayout anTable = (TableLayout) anTableRow.getParent();
itsLinearLayout.removeView(anTable);
}
};
/**
* Save the values to db.
*/
private void saveCategory()
{
CategoryService aCategoryService = DatabaseService.getInstance(this).getCategoryService();
aCategoryService.save(getModel());
Log.d(CLASSNAME, "successfully saved model");
Intent anIntent = new Intent(this, CategoriesListActivity.class);
startActivity(anIntent);
}
/**
* performs the delete.
*/
private void deleteCategory()
{
}
/**
* Returns the model object. It gets the values from the EditText views and sets to the model.
* #return
*/
private CategoryModel getModel()
{
CategoryModel aCategoryModel = new CategoryModel();
try
{
EditText anCategoryNameEditText = (EditText) findViewById(R.id.categoryNameEditText);
aCategoryModel.setCategoryName(anCategoryNameEditText.getText().toString());
for(int i= 0; i< itsLinearLayout.getChildCount(); i++)
{
View aTableLayOutView = itsLinearLayout.getChildAt(i);
if(aTableLayOutView instanceof TableLayout)
{
for(int j= 0; j< ((TableLayout) aTableLayOutView).getChildCount() ; j++ );
{
TableRow anTableRow = (TableRow) ((TableLayout) aTableLayOutView).getChildAt(i);
EditText anEditText = (EditText) anTableRow.getChildAt(0);
if(StringUtils.isNullOrEmpty(anEditText.getText().toString()))
{
// show a validation message.
//return aCategoryModel;
}
setValuesToModel(aCategoryModel, i + 1, anEditText.getText().toString());
}
}
}
}
catch (Exception anException)
{
Log.d(CLASSNAME, "Exception occured"+anException);
}
return aCategoryModel;
}
/**
* Sets the value to model.
* #param theModel
* #param theFieldIndexNumber
* #param theFieldValue
*/
private void setValuesToModel(CategoryModel theModel, int theFieldIndexNumber, String theFieldValue)
{
switch (theFieldIndexNumber)
{
case 1 :
theModel.setField1(theFieldValue);
break;
case 2 :
theModel.setField2(theFieldValue);
break;
case 3 :
theModel.setField3(theFieldValue);
break;
case 4 :
theModel.setField4(theFieldValue);
break;
case 5 :
theModel.setField5(theFieldValue);
break;
case 6 :
theModel.setField6(theFieldValue);
break;
case 7 :
theModel.setField7(theFieldValue);
break;
case 8 :
theModel.setField8(theFieldValue);
break;
case 9 :
theModel.setField9(theFieldValue);
break;
case 10 :
theModel.setField10(theFieldValue);
break;
case 11 :
theModel.setField11(theFieldValue);
break;
case 12 :
theModel.setField12(theFieldValue);
break;
case 13 :
theModel.setField13(theFieldValue);
break;
case 14 :
theModel.setField14(theFieldValue);
break;
case 15 :
theModel.setField15(theFieldValue);
break;
}
}
}
2. Write the Layout xml as given below.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:background="#006699"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.blmsr.manager.CategoryEditorActivity">
<LinearLayout
android:id="#+id/addCategiryNameItem"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="#+id/categoryNameTextView"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:text="#string/lbl_category_name"
android:textStyle="bold"
/>
<TextView
android:id="#+id/categoryIconName"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:text="#string/lbl_category_icon_name"
android:textStyle="bold"
/>
</LinearLayout>
<LinearLayout
android:id="#+id/linearLayout1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<EditText
android:id="#+id/categoryNameEditText"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:hint="#string/lbl_category_name"
android:inputType="textAutoComplete" />
<ScrollView
android:id="#+id/scrollView1"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:id="#+id/linearLayout2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<LinearLayout
android:id="#+id/linearLayout3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
</LinearLayout>
<ImageButton
android:id="#+id/addField"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_below="#+id/addCategoryLayout"
android:src="#drawable/ic_input_add"
android:onClick="addField"
/>
</LinearLayout>
</ScrollView>
</LinearLayout>
Once you finished your view will as shown below
//MainActivity :
package com.edittext.demo;
import android.app.Activity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Toast;
public class MainActivity extends Activity {
private EditText edtText;
private LinearLayout LinearMain;
private Button btnAdd, btnClear;
private int no;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edtText = (EditText)findViewById(R.id.edtMain);
btnAdd = (Button)findViewById(R.id.btnAdd);
btnClear = (Button)findViewById(R.id.btnClear);
LinearMain = (LinearLayout)findViewById(R.id.LinearMain);
btnAdd.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (!TextUtils.isEmpty(edtText.getText().toString().trim())) {
no = Integer.parseInt(edtText.getText().toString());
CreateEdittext();
}else {
Toast.makeText(MainActivity.this, "Please entere value", Toast.LENGTH_SHORT).show();
}
}
});
btnClear.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
LinearMain.removeAllViews();
edtText.setText("");
}
});
/*edtText.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,int after) {
}
#Override
public void afterTextChanged(Editable s) {
}
});*/
}
protected void CreateEdittext() {
final EditText[] text = new EditText[no];
final Button[] add = new Button[no];
final LinearLayout[] LinearChild = new LinearLayout[no];
LinearMain.removeAllViews();
for (int i = 0; i < no; i++){
View view = getLayoutInflater().inflate(R.layout.edit_text, LinearMain,false);
text[i] = (EditText)view.findViewById(R.id.edtText);
text[i].setId(i);
text[i].setTag(""+i);
add[i] = (Button)view.findViewById(R.id.btnAdd);
add[i].setId(i);
add[i].setTag(""+i);
LinearChild[i] = (LinearLayout)view.findViewById(R.id.child_linear);
LinearChild[i].setId(i);
LinearChild[i].setTag(""+i);
LinearMain.addView(view);
add[i].setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//Toast.makeText(MainActivity.this, "add text "+v.getTag(), Toast.LENGTH_SHORT).show();
int a = Integer.parseInt(text[v.getId()].getText().toString());
LinearChild[v.getId()].removeAllViews();
for (int k = 0; k < a; k++){
EditText text = (EditText) new EditText(MainActivity.this);
text.setId(k);
text.setTag(""+k);
LinearChild[v.getId()].addView(text);
}
}
});
}
}
#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;
}
}
// Now add xml main
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:orientation="horizontal" >
<EditText
android:id="#+id/edtMain"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_weight="1"
android:ems="10"
android:hint="Enter value" >
<requestFocus />
</EditText>
<Button
android:id="#+id/btnAdd"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:text="Add" />
<Button
android:id="#+id/btnClear"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:text="Clear" />
</LinearLayout>
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="10dp" >
<LinearLayout
android:id="#+id/LinearMain"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
</LinearLayout>
</ScrollView>
// now add view xml file..
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:orientation="horizontal" >
<EditText
android:id="#+id/edtText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:ems="10" />
<Button
android:id="#+id/btnAdd"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:text="Add" />
</LinearLayout>
<LinearLayout
android:id="#+id/child_linear"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="30dp"
android:layout_marginRight="10dp"
android:layout_marginTop="5dp"
android:orientation="vertical" >
</LinearLayout>

Categories

Resources