Android Studio creating board programmatically - java

I am currently trying to create my first board Android game and struggling with my layout. My code only creates one row of the board. I have read almost every post but could not find anything useful.
public class Nonogram extends AppCompatActivity {
private Field field = new Field(10,10,75);
private ImageView[][] board = new ImageView[field.getRowCount()][field.getColumnCount()];
Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_nonogram);
context = this;
draw();
}
private void draw(){
RelativeLayout relativeLayout = (RelativeLayout) findViewById(R.id.nonogram);
for(int row = 0; row < field.getRowCount(); row ++) {
LinearLayout rowl = new LinearLayout(context);
for (int column = 0; column < field.getColumnCount(); column++) {
board[row][column] = new ImageView(context);
if (field.getUserTiles()[row][column].getState() == TileState.FILLED) {
board[row][column].setBackgroundResource(R.drawable.filled);
} else if (field.getUserTiles()[row][column].getState() == TileState.EMPTY) {
board[row][column].setBackgroundResource(R.drawable.empty);
} else {
board[row][column].setBackgroundResource(R.drawable.marked);
}
rowl.addView(board[row][column]);
}
relativeLayout.addView(rowl);
}
}
The XML is just the Relative Layout.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:id="#+id/nonogram"
android:background="#drawable/menu_background"
tools:context="pocketfun.org.pocketfun.nonogram.Nonogram">
</RelativeLayout>

Use LinearLayout as root instead (don't forget the android:orientation="vertical"):
<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:orientation="vertical"
android:layout_height="match_parent"
android:id="#+id/nonogram"
android:background="#drawable/menu_background"
tools:context="pocketfun.org.pocketfun.nonogram.Nonogram">
</LinearLayout>
And adjust your code:
LinearLayout rootLayout = (LinearLayout) findViewById(R.id.nonogram);
for(int row = 0; row < field.getRowCount(); row ++) {
[...]
rootLayout.addView(row1);
}

Related

Why My programatically created LinearLayouts not shown

I'm trying to create a LinearLayout programmatically but for some reason it is not shown and I have no errors in Logcat or Run terminals.
Here is my Java code:
public class MainActivity extends AppCompatActivity {
String [] arr = {"1","2","3"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final LinearLayout parent = findViewById(R.id.rootLayout);
LinearLayout child;
for(int i = 0; i < arr.length; i++) {
child = new LinearLayout(this);
child.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
child.setOrientation(LinearLayout.VERTICAL);
child.setBackgroundColor(Color.YELLOW);
parent.addView(child);
}
}
}
and my XML:
<?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:id="#+id/rootLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
</LinearLayout>
What I'm trying to achieve is to have 3 LinearLayouts created according to the array length as I will pass some TextViews to them later
I tried to follow the answer I found Creating LinearLayout Programmatically/Dynamically with Multiple Views but still cannot see the LinearLayouts created on the simulator.
Here is how it shows:
Simulator Preview
I'm unsure what am I doing wrong?
Thank you for the hints and help.
Used the below and this fixed the issue:
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
lp.height = 150;

Dynamic ListView With EditTexts Android

I have a ListView in my Android application that uses a CustomAdapterClass. The ListView is populated with rows that contain 2 Edit Texts per row. This is fine, the problem I'm having is the ListView is dynamic, i.e. I have added a button that will append on a new row by calling notifyDataSetChanged(); however this clears the whole list.
How can I keep the text that has been entered into the EditTexts when a new row is appended? Code below:
Activity.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res
/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent" android:layout_height="match_parent">
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:descendantFocusability="afterDescendants"
android:id="#+id/listViewAddPeople">
</ListView>
<android.support.design.widget.FloatingActionButton
android:id="#+id/fabAddPerson"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:src="#mipmap/ic_launcher"
app:backgroundTint="#FFFFFF"
android:elevation="6dp"
/>
</RelativeLayout>
Row.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res
/android"
android:layout_width="match_parent" android:layout_height="match_parent">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/personNameEditText"
android:hint="Enter Persons Full Name"/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/personPhoneNoEditText"
android:layout_below="#+id/personNameEditText"
android:hint="Enter Phone No. (Optional)"/>
</RelativeLayout>
Java Class:
public class AddPeopleNewProcedureActivity extends AppCompatActivity {
private ListView addPeopleListView;
private CustomAdapterClass customAdapter;
private FloatingActionButton fab;
private int lineCount;
private EditText personsNameET;
private EditText personsPhoneET;
private List<String> personsName;
private List<String> personsPhone;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.addpeoplenew_activity);
setupActivityReferences();
inflateListView();
setupClickListeners();
}
private void setupClickListeners() {
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
lineCount = lineCount +1;
personsName.clear();
personsPhone.clear();
customAdapter.notifyDataSetChanged();
}
});
}
private void inflateListView() {
customAdapter = new CustomAdapterClass();
addPeopleListView.setAdapter(customAdapter);
}
private void setupActivityReferences() {
addPeopleListView = (ListView) findViewById(R.id.listViewAddPeople);
fab = findViewById(R.id.fabAddPerson);
personsNameET = (EditText) findViewById(R.id.personNameEditText);
personsPhoneET = (EditText) findViewById(R.id.personPhoneNoEditText);
lineCount = 1;
}
public class CustomAdapterClass extends BaseAdapter {
#Override
public int getCount() {
return lineCount;
}
#Override
public Object getItem(int i) {
return null;
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
view =
getLayoutInflater().inflate(R.layout.row_addpersonnew,null);
final int rowClicked = i;
return view;
}
}
}
Any help is appreciated!
I have added a button that will append on a new row by calling
notifyDataSetChanged();
I can't see any append actions when someone clicks that button. I see that you clear both of your lists, personsName and personsPhone and after that you notify your adapter that those lists are empty.
Write what really want to be done inside the onClick().

row generator with textviews

This is my code for a n app in which i want to add textviews in a row
dynamically on click of a button and not working can you tell me whats wrong with the code,i am just a beginner.
thanking you in anticipation.
public class MainActivity extends AppCompatActivity {
Button save;
TableLayout tableLayout;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button save = (Button) findViewById(R.id.save);
TableLayout tableLayout = (TableLayout) findViewById(R.id.table1);
save.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
TableRow tableRow;
TextView textView;
TableLayout tableLayout = (TableLayout) findViewById(R.id.table1);
for (int i = 0; i < 4; i++) {
tableRow = new TableRow(getApplicationContext());
for (int j = 0; j < 3; j++) {
textView = new TextView(getApplicationContext());
textView.setText("####");
textView.setPadding(20, 20, 20, 20);
tableRow.addView(textView);
}
tableLayout.addView(tableRow);
}}});
setContentView(tableLayout);
}
}
and my xml layout
<?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:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
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.kalla.monu.saplist.MainActivity">
<TableLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentTop="true"
android:layout_alignParentEnd="true"
android:layout_marginEnd="28dp"
android:layout_marginTop="160dp"
android:id="#+id/table1"
android:background="#color/colorPrimaryDark">
<TableRow
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#android:color/darker_gray"/>
<TableRow
android:layout_width="match_parent"
android:layout_height="match_parent"
android:backgroundTint="#android:color/holo_green_dark" />
<TableRow
android:layout_width="match_parent"
android:layout_height="match_parent" />
<TableRow
android:layout_width="match_parent"
android:layout_height="match_parent" />
</TableLayout>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="save"
android:id="#+id/save" />
</RelativeLayout>
Try this,
I assume you are trying to add tablerows and textviews both dynamically. So I have removed existing tablerows from layout xml.
TableLayout tableLayout = (TableLayout) findViewById(R.id.table1);
save.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
TableRow tableRow;
TextView textView;
for (int i = 0; i < 4; i++) {
tableRow = new TableRow(this);
for (int j = 0; j < 3; j++) {
textView = new TextView(this);
textView.setText("####");
textView.setPadding(20, 20, 20, 20);
tableRow.addView(textView);
}
table1.addView(tableRow);
}}});
In XML:
<TableLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/table1"/>

Unable to populate ListView with ArrayList

I'm trying to make an audio recorder for which I want to display a list of recordings done till now.
I'm able to get the list recorded files from my SD card in to an ArrayList, but my app crashes when it tries to populate the list view.
ListRecordings.java is called using an Intent from MainActivity.java.
Here is the for ListRecordings.java:
public class ListRecordings extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.listrecordings);
ListView lv;
String path = Environment.getExternalStorageDirectory()
.getAbsolutePath() + "/MyAudioRecorder";
ArrayList<String> FilesInFolder = GetFiles(path);
lv = (ListView) findViewById(R.id.filelist);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.textlayout,
FilesInFolder);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
// Clicking on items
}
});
}
public ArrayList<String> GetFiles(String DirectoryPath) {
ArrayList<String> MyFiles = new ArrayList<String>();
File f = new File(DirectoryPath);
f.mkdirs();
File[] files = f.listFiles();
if (files.length == 0)
return null;
else {
for (int i = 0; i < files.length; i++)
MyFiles.add(files[i].getName());
}
return MyFiles;
}
}
Here's the code for listrecordings.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" >
<ListView
android:id="#+id/filelist"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>
Here's the code for textlayout.xml
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/label"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dp"
android:textSize="16sp"
android:textStyle="bold" >
</TextView>
Any help is appreciated.
I've just started with android so excuse me if i made any lame mistakes.
Thanks
You missing this line in onCreate()
super.onCreate(savedInstanceState);
Add something like this
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.textlayout,
R.id.textview_id_in_textlayout,FilesInFolder);
I hope this will help.

add((RelativeLayout) findViewById) to ArrayList<RelativeLayout>

I have the following code:
public class MainActivity extends Activity implements OnClickListener {
public ArrayList<RelativeLayout> buttons = new ArrayList<RelativeLayout>();
public ArrayList<Integer> drawableId = new ArrayList<Integer>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_layout);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
linear = (LinearLayout) findViewById(R.id.Rlayout);
scrool = (ScrollView) findViewById(R.id.scrool);
for (int i = 0; i < buttons.size(); i++) {
{
String buttonID = "Llayout" + i;
int resID = getResources().getIdentifier(buttonID, "id",
getPackageName());
//The problem is here
buttons.get(i).add((RelativeLayout) findViewById(resID));
buttons.get(i).setOnClickListener(this);
drawableId.add(getResources().getIdentifier("supa" + i, "drawable", getPackageName()));
}
}
}
#Override
public void onClick(View v) {
for (int i = 0; i < buttons.size(); i++) {
if (buttons.get(i).getId() == v.getId()) {
index = i;
Intent trimite = new Intent(MainActivity.this, RecipeView.class);
Bundle colet = new Bundle();
colet.putString("key", Content.RETETE[i]);
colet.putInt("keyimg", drawableId.get(i));
trimite.putExtras(colet);
startActivity(trimite);
break;
}
}
}
}
I cannot get this to work:
buttons.get(i).add((RelativeLayout) findViewById(resID));
Java error says that: add((RelativeLayout) is undefined for the type RelativeLayout.
The add method works for ArrayList drawableId, one line below but not for buttons. Can someone, please, help me?
Here is my xml layout:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/scrool"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:fillViewport="true"
android:scrollbars="vertical"
tools:context=".MainActivity"
tools:ignore="MergeRootFrame" >
<LinearLayout
android:id="#+id/Rlayout"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:keepScreenOn="true"
android:orientation="vertical" >
<RelativeLayout
android:id="#+id/Llayout0"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:clickable="true"
android:focusable="true"
android:onClick="onClick"
android:orientation="vertical" >
<ImageView
android:id="#+id/iv0"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_gravity="left"
android:contentDescription="#string/desc"
android:src="#drawable/supa0" />
<TextView
android:id="#+id/tv0"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="#string/supa"
android:textAppearance="?android:attr/textAppearanceLarge" />
</RelativeLayout>
<RelativeLayout
android:id="#+id/Llayout1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:clickable="true"
android:focusable="true"
android:onClick="onClick"
android:orientation="vertical" >
<ImageView
android:id="#+id/iv1"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_gravity="left"
android:contentDescription="#string/desc"
android:src="#drawable/supa0" />
<TextView
android:id="#+id/tv1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="#string/supa1"
android:textAppearance="?android:attr/textAppearanceLarge" />
</RelativeLayout>
</LinearLayout>
</ScrollView>
I made buttons from RelativeLayouts. Each RelativeLayout button has text and an icon next to the text. All of the RelativeLayouts buttons are in a LinearLayout so that they align under each other.
When the RelativeLayouts buttons and the ArrayList drawableId were simple arrays it worked great but I don't want to modify the array every time I add a new RelativeLayout button.
Any suggestions?
The RelativeLayout class has no add() method.
buttons is an ArrayList of RelativeLayouts. When you call buttons.get(i), you get a single RelativeLayout object. Since RelativeLayout has no add() method, you get this error.
It isn't entirely clear what your intent is with this code, but I am assuming that you are trying to add each of your RelativeLayouts to the buttons list.
If this is correct, you just need to remove the get(i) call, making that line into
buttons.add((RelativeLayout) findViewById(resID));
Try this way,hope this will help you to solve your problem.
public class MainActivity extends Activity implements View.OnClickListener {
private ArrayList<RelativeLayout> buttons = new ArrayList<RelativeLayout>();
private ArrayList<Integer> drawableId = new ArrayList<Integer>();
private LinearLayout linear;
private ScrollView scrool;
private int index;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
linear = (LinearLayout) findViewById(R.id.Rlayout);
scrool = (ScrollView) findViewById(R.id.scrool);
for (int i = 0; i < linear.getChildCount(); i++) {
{
String buttonID = "Llayout" + i;
int resID = getResources().getIdentifier(buttonID, "id",getPackageName());
buttons.add((RelativeLayout)findViewById(resID));
buttons.get(i).setOnClickListener(this);
drawableId.add(getResources().getIdentifier("supa" + i, "drawable", getPackageName()));
}
}
}
#Override
public void onClick(View v) {
for (int i = 0; i < buttons.size(); i++) {
if (buttons.get(i).getId() == v.getId()) {
index = i;
Toast.makeText(MyActivity.this,String.valueOf(index),Toast.LENGTH_SHORT).show();
Intent trimite = new Intent(MainActivity.this, RecipeView.class);
Bundle colet = new Bundle();
colet.putString("key", Content.RETETE[i]);
colet.putInt("keyimg", drawableId.get(i));
trimite.putExtras(colet);
startActivity(trimite);
break;
}
}
}
}

Categories