Getting the sum of variables and numbers from columns using gridlayout - java

This is my very first post here and i am very new to programming, ive started a project in android studio but i've become stuck on a couple of things because my lack of knowledge.
I have three different tabs and i want to make the calculation on the second one.
So my question is how do i calculate data in columns inside of the gridlayout?
My component tree looks like this in tab2:
RelativeLayout>Scrollview>Gridlayout.
I have inserted several textedits on column 2 and 3 and my goal is to make calculations based on their input and then insert them as results at the bottom of the tab.
2nd column includes numbers only and the 3rd column includes variables.
I want to make the variables the user enters on the 3rd column equal to numbers, for example A=20 B=17.5 etc
So when its calculating its automatically changing the variable to the
equal number.
How do i proceed?
Tab2 java class:
package com.example.minmerit;
/**
* Created by lukin on 2017-06-14.
*/
import android.app.Activity;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class Tab2Betyg extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.tab2betyg, container, false);
return rootView;
}
}
Tab2 layout 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="450dp"
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.example.minmerit.MainActivity$PlaceholderFragment">
<TextView
android:id="#+id/textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<ScrollView
android:id="#+id/scrollView"
android:layout_width="match_parent"
android:layout_height="600dp"
android:layout_below="#id/textview">
<GridLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<EditText
android:id="#+id/POÄNG"
android:layout_width="67dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_row="1"
android:ems="10"
android:fontFamily="monospace"
android:inputType="number"
android:text="100"
android:textAlignment="center"
android:textColor="#android:color/black" />

First, give your EditTexts some proper IDs, like
<EditText
android:id="#+id/number_1"
...
Then in eg. onViewCreated make changeListeners:
EditText number_1 = (EditText) findViewById(R.id.number_1);
number_1.addTextChangedListener( changeListener );
// change listeners for other fields
TextWatcher changeListener = new TextWatcher() {
#Override
public void afterTextChanged(Editable s) {}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
#Override
public void onTextChanged(CharSequence s, int start,
int before, int count) {
int a = Integer.parseInt(s);
// do something with "a"
}
});

Related

How do I associate Views in a GridLayout with its corresponding Objects?

I'm currently working on an Activity in my game that provides two important functionalities:
determining the amount of Players for a game session
determining what Roles from the predetermined ArrayList allRoles will be present in this game session (all Roles selected here will be randomly assigned to a list of players later)
Every Role has different abilities and values, so each Role is its own object that inherits from the Role.java class.
For example, the allRoles-ArrayList contains objects like Mage, Mountainclimber, Bear, Wise_Man and more, all inheriting from the Role class.
Role.java
public class Role {
protected String imageName;
protected int count;
protected int maxCount;
public Role(int maxCount){
this.imageName = null;
this.count = 0;
this.maxCount = maxCount;
}
}
Now, in my Activity there's a GridLayout (will be built and then added to a LinearLayout) containing one role_entry.xml for each element in allRoles.
Some Roles can be in the game multiple times, while there can be only one of others.
The TextView with the id "roleCount" shows how many instances of a Role the user wants in his game.
This number can be adjusted with the "+" and "-" Buttons, within the Role's bounds (0-maxCount).
NOTE: I want the Buttons to adjust the count value of its corresponding Role as well, but I don't know how.
I also don't know which Role to get 'maxCount' from when a Button is pressed.
My question aims to solve these problems.
Possible user selection:
3x Mountainclimber, 2x Mage, 1x Bear, 1x Wise_Man = 7 Players in total (user can choose 7 Player profiles later)
role_entry.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto">
<ImageView
android:id="#+id/roleImage"
android:layout_width="120dp"
android:layout_height="120dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/roleCount"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="6dp"
android:layout_marginBottom="6dp"
android:text="0"
android:textSize="#dimen/roleSelection_roleCount_ts"
android:textColor="#color/white"
app:layout_constraintBottom_toBottomOf="#id/roleImage"
app:layout_constraintEnd_toEndOf="#id/roleImage"/>
<LinearLayout
android:layout_width="100dp"
android:layout_height="wrap_content"
android:orientation="horizontal"
app:layout_constraintTop_toBottomOf="#id/roleImage"
app:layout_constraintStart_toStartOf="#id/roleImage"
app:layout_constraintEnd_toEndOf="#id/roleImage"
android:layout_marginTop="6dp"
android:layout_marginBottom="6dp">
<androidx.appcompat.widget.AppCompatButton
android:id="#+id/roleSubtract"
android:layout_width="90dp"
android:layout_height="40dp"
android:layout_weight="1"
android:text="-"
android:textSize="#dimen/button_ts"
android:enabled="false"
android:textColor="#color/black"
android:background="#drawable/button_left_custom"/>
<androidx.appcompat.widget.AppCompatButton
android:id="#+id/roleAdd"
android:layout_width="90dp"
android:layout_height="40dp"
android:layout_weight="1"
android:text="+"
android:textSize="#dimen/button_ts"
android:background="#drawable/button_right_custom"/>
</LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
RoleSelection.java (my Activity)
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.GridLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import java.util.ArrayList;
public class RoleSelection extends AppCompatActivity {
//Variables
ArrayList<Role> allRoles = null;
//Views
private TextView totalRoleCount = null;
private LinearLayout scrollList = null;
private GridLayout basegameList = null;
private Button next = null;
private Button back = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_role_selection);
//initializing views
totalRoleCount = findViewById(R.id.total_role_count);
scrollList = findViewById(R.id.scrollList);
//initializing 'allRoles' in the order it will be shown in in the GridLayout
allRoles = new ArrayList<>();
allRoles.add(new Mountainclimber());
allRoles.add(new Mage());
allRoles.add(new Bear());
allRoles.add(new Wise_Man());
//adding Roles to GridLayout
//
//building GridLayout to contain Role-entries
GridLayout basegameList = new GridLayout(this);
basegameList.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
basegameList.setColumnCount(3);
basegameList.setUseDefaultMargins(true);
for(Role r: allRoles){
//initializing 'roleEntry'
View roleEntry = getLayoutInflater().inflate(R.layout.role_selection_entry, null);
ImageView roleImage = roleEntry.findViewById(R.id.roleImage);
TextView roleCount = roleEntry.findViewById(R.id.roleCount);
Button roleSubtract = roleEntry.findViewById(R.id.roleSubtract);
Button roleAdd = roleEntry.findViewById(R.id.roleAdd);
//setting Image
roleImage.setImageResource(this.getResources().getIdentifier("drawable/" + r.imageName, null, this.getPackageName()));
//just to be safe
roleCount.bringToFront();
//'Subtract'-Button of roleEntry
roleSubtract.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//TODO: pseudocode:
// check if decrement would hit 0:
// if yes, decrement and set 'enabled' of roleSubtract to "false" --> this role can no longer be decremented
// else:
// decrement
}
});
//'Add'-Button of roleEntry
roleAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//TODO: pseudocode:
// check if increment would hit 'maxCount':
// if yes, increment and set 'enabled' of roleAdd to "false" --> this role can no longer be incremented
// else:
// increment
}
});
//adding 'roleEntry' to GridLayout
basegameList.addView(roleEntry);
}
//adding Gridlayout to scrollList
//NOTE: scrollList exists because more Gridlayouts and Seperators may be added later - when I decide to make extensions of the game
scrollList.addView(basegameList);
next = findViewById(R.id.navigation_bar_next);
//TODO: set onClickListener for next --> PlayerSelection
back = findViewById(R.id.navigation_bar_back);
back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) { gotoPlayerCreation(); }
});
}
//TODO: create gotoPlayerSelection() function
public void gotoPlayerCreation(){
Intent intent = new Intent(this, PlayerCreation.class);
startActivity(intent);
}
}
role_selection.xml (my Activity)
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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"
tools:context=".RoleSelection"
tools:ignore="HardcodedText">
<androidx.constraintlayout.widget.ConstraintLayout
android:id="#+id/info_container"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<LinearLayout
android:id="#+id/explanation"
android:layout_width="0dp"
android:layout_height="60dp"
android:layout_marginStart="#dimen/marginStart_default"
android:layout_marginTop="#dimen/marginTop_default"
android:layout_marginEnd="60dp"
android:orientation="horizontal"
app:layout_constraintEnd_toStartOf="#+id/total_selected"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:text="Wähle die Karten aus, die mitspielen:"
android:textSize="#dimen/standard_ts" />
</LinearLayout>
<TextView
android:id="#+id/total_selected"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Gesamt: "
android:textSize="#dimen/standard_ts"
app:layout_constraintBottom_toBottomOf="#+id/explanation"
app:layout_constraintEnd_toStartOf="#+id/total_role_count"
app:layout_constraintTop_toTopOf="#+id/explanation" />
<TextView
android:id="#+id/total_role_count"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="#dimen/marginEnd_default"
android:text="0"
android:textSize="#dimen/standard_ts"
app:layout_constraintBottom_toBottomOf="#id/total_selected"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="#+id/total_selected" />
<TextView
android:id="#+id/recommendations"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="#dimen/marginStart_default"
android:layout_marginEnd="#dimen/marginEnd_default"
android:layout_marginBottom="#dimen/marginBottom_default"
android:text="Empfehlung: "
android:textSize="#dimen/standard_ts"
app:layout_constraintTop_toBottomOf="#id/explanation"
app:layout_constraintBottom_toBottomOf="parent"/>
</androidx.constraintlayout.widget.ConstraintLayout>
<ScrollView
android:id="#+id/roleSelection_scrollView"
android:layout_width="match_parent"
android:layout_height="0dp"
app:layout_constraintTop_toBottomOf="#+id/info_container"
app:layout_constraintBottom_toTopOf="#id/navigation_container">
<LinearLayout
android:id="#+id/scrollList"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
</LinearLayout>
</ScrollView>
<LinearLayout
android:id="#+id/navigation_container"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
app:layout_constraintBottom_toBottomOf="parent">
<include layout="#layout/navigation_bar" />
</LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
How do I associate a role_entry with its corresponding object in ArrayList allRoles?
Please keep in mind that I'm new to android development, and thank you all in advance :D

Is there a way to display continuous data on a List View in Android Studio?

I'm currently doing a project that requires me to continuously display data from a Bluetooth device, in this case, the weight measurements from four different sensors.
I have tried creating a List View using a custom adapter but it would only display the set of inputs once. The data shown on the List View would only update if I exit and re-enter the fragment.
I have been trying to find a way to continuously add in a new set of inputs onto the List View while retaining the previous data on top but I can't seem to find a good reference for it.
This is an example of what my List View looks like:
My Code:
My CustomAdapter
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import java.util.List;
import static com.shoeinsoleweight.bluetooth_java_fragment.main_activity.InputValue1;
import static com.shoeinsoleweight.bluetooth_java_fragment.main_activity.InputValue2;
import static com.shoeinsoleweight.bluetooth_java_fragment.main_activity.InputValue3;
import static com.shoeinsoleweight.bluetooth_java_fragment.main_activity.InputValue4;
public class Adapter_inputs extends ArrayAdapter<Model_inputs> {
private final int resourceLayout;
public Adapter_inputs(Context context, int resourceLayout, List<Model_inputs> inputsList) {
super(context, resourceLayout, inputsList);
this.resourceLayout = resourceLayout;
}
public View getView(int position, View convertView, ViewGroup parent){
View v = convertView;
if(v == null){
LayoutInflater layoutInflater = LayoutInflater.from(getContext());
v = layoutInflater.inflate(resourceLayout, null);
}
Model_inputs inputs = getItem(position);
if(inputs != null){
TextView input1TV = (TextView) v.findViewById(R.id.InputValue1);
TextView input2TV = (TextView) v.findViewById(R.id.InputValue2);
TextView input3TV = (TextView) v.findViewById(R.id.InputValue3);
TextView input4TV = (TextView) v.findViewById(R.id.InputValue4);
if(input1TV != null){
input1TV.setText("Input Value 1:" + InputValue1);
}
if(input2TV != null){
input2TV.setText("Input Value 2:" + InputValue2);
}
if(input3TV != null){
input3TV.setText("Input Value 3:" + InputValue3);
}
if(input4TV != null){
input4TV.setText("Input Value 4:" + InputValue4);
}
}
return v;
}
}
My Model
package com.shoeinsoleweight.bluetooth_java_fragment;
public class Model_inputs{
String Input1;
String Input2;
String Input3;
String Input4;
public Model_inputs(String Input1, String Input2, String Input3, String Input4){
this.Input1 = Input1;
this.Input2 = Input2;
this.Input3 = Input3;
this.Input4 = Input4;
}
public String getInput1() {
return Input1;
}
public String getInput2() {
return Input2;
}
public String getInput3() {
return Input3;
}
public String getInput4() {
return Input4;
}
}
My Fragment
public class history_fragment extends Fragment {
private View decorView;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.history_fragment, container, false);
}
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
List<Model_inputs> inputsList = new ArrayList<>();
Model_inputs inputs = new Model_inputs("a", "b", "c", "d");
inputsList.add(inputs);
ListView listView = (ListView) view.findViewById(R.id.InputValue_LV);
Adapter_inputs adapter_inputs = new Adapter_inputs(requireActivity(), R.layout.row_inputs, inputsList);
listView.setAdapter(adapter_inputs);
}
}
XML file for each set of data
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#BFFFFFFF"
android:backgroundTint="#2B2B2B"
android:orientation="vertical">
<TextView
android:id="#+id/InputValue1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:text="Input Value 1:"
android:textColor="#FFF"
android:textSize="15sp"
android:textStyle="bold" />
<TextView
android:id="#+id/InputValue2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:text="Input Value 2:"
android:textColor="#FFF"
android:textSize="15sp"
android:textStyle="bold" />
<TextView
android:id="#+id/InputValue3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:text="Input Value 3:"
android:textColor="#FFF"
android:textSize="15sp"
android:textStyle="bold" />
<TextView
android:id="#+id/InputValue4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:text="Input Value 4:"
android:textColor="#FFF"
android:textSize="15sp"
android:textStyle="bold" />
</LinearLayout>
</LinearLayout>
XML file for fragment
<?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:orientation="vertical"
android:background="#drawable/nightsky"
tools:context=".history_fragment">
<FrameLayout
android:id="#+id/fl_navBar"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#+id/bottom_nav">
<TextView
android:id="#+id/History_Text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="30dp"
android:background="#null"
android:ems="10"
android:fontFamily="casual"
android:text="#string/history"
android:textAlignment="center"
android:textColor="#FFFFFF"
android:textSize="24sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<ListView
android:id="#+id/InputValue_LV"
android:layout_width="match_parent"
android:layout_height="585dp"
android:layout_marginTop="80dp"
android:background="#BFFFFFFF"
android:backgroundTint="#2B2B2B" />
</FrameLayout>
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="#+id/bottom_nav"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:background="#00019184"
app:itemIconTint="#FFFFFF"
app:itemTextColor="#FFFFFF"
app:menu="#menu/nav_menu" />
</RelativeLayout>
Instead of using List user ArrayList in the adapter. Then, when the bluetooth sends the data (this will be a listener which will be capturing the bluetooth data, probably a service or something similar), add the data set to the array list that you are passing to the Adapter and call the onDataSetChanged() function on adapter which is a built-in method to notify the adapter that dataset has been changed. like
list.add(new Model_inputs("a", "b", "c", "d"));
adapter.notifyDataSetChanged();
Here, "new Model_inputs("a", "b", "c", "d")" will be the new data set sent by the bluetooth device.
I would recommend to use RecyclerView instead of ListView, which provides a better way of inflating the views. i.e. it recycles the views upon scrolling.

Can anyone explain me how the execution process runs in this java code for Fragments in Android Studio [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I wrote this code according to the video tutorial found here
about Android Fragments, but I can't understand how the flow of execution runs through these codes. As in the tutorial I have made two fragments alone with the Main Activity. The whole program works fine, but I can't understand how the execution flow goes. Please be kind enough to explain me. Here are my source codes, I am
really sorry as they are too long, I posted all of my code. This is the Main Activity.java
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends ActionBarActivity implements top_layout_fragment.TopSelectionListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
//overiding the method from the interface
#Override
public void createMeme(String top, String bottom) {
bottom_layout_fragment bottomLayoutFragment = (bottom_layout_fragment) getSupportFragmentManager().findFragmentById(R.id.fragment2);
bottomLayoutFragment.setText(top, bottom);
}
#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_main, 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.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
this is the 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:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".MainActivity">
<fragment
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:name="com.example.kasun.fragments.top_layout_fragment"
android:id="#+id/fragment"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
tools:layout="#layout/top_layout_fragment" />
<fragment
android:layout_width="320dp"
android:layout_height="320dp"
android:name="com.example.kasun.fragments.bottom_layout_fragment"
android:id="#+id/fragment2"
tools:layout="#layout/bottum_layout_fragment"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
this is the top_layout_fragment.java
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.View;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.Button;
import android.app.Activity;
import java.util.ServiceConfigurationError;
public class top_layout_fragment extends Fragment {
private static EditText firstText, secondText;
TopSelectionListener activityCommand;
public interface TopSelectionListener {
public void createMeme(String top, String bottom);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
activityCommand = (TopSelectionListener) activity;
}
catch(ClassCastException e){
throw new ClassCastException (activity.toString());
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.top_layout_fragment, container, false);
firstText = (EditText) view.findViewById(R.id.firstText);
secondText = (EditText) view.findViewById(R.id.secondText);
final Button button = (Button) view.findViewById(R.id.button);
button.setOnClickListener(
new View.OnClickListener() {
public void onClick(View v) {
buttonClicked(v);
}
}
);
return view;
}
public void buttonClicked(View view) {
activityCommand.createMeme(firstText.getText().toString(), secondText.getText().toString());
}
}
this is top_layout_fragment.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:id="#+id/firstText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:width="320dp"
android:layout_marginTop="20dp"
android:layout_centerHorizontal="true"
/>
<EditText
android:id="#+id/secondText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:width="320dp"
android:layout_marginTop="20dp"
android:layout_centerHorizontal="true"
android:layout_below="#id/firstText"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_below="#+id/secondText"
android:layout_marginTop="20dp"
android:text="#string/button_Texg"
android:id="#+id/button" />
</RelativeLayout>
this is the bottom_layout_fragment.java
package com.example.kasun.fragments;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.View;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.widget.TextView;
public class bottom_layout_fragment extends Fragment {
private TextView topText,bottomText;
// need to overide the onCreateViewMethod
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.bottum_layout_fragment,container,false);
topText=(TextView)view.findViewById(R.id.topText);
bottomText=(TextView)view.findViewById(R.id.bottomText);
return view;
}
public void setText(String topText,String bottomText){
this.topText.setText(topText);
this.bottomText.setText(bottomText);
}
}
this is the bottom_layout_fragment.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"
android:background="#drawable/image1">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Large Text"
android:id="#+id/topText"
android:layout_marginTop="34dp"
android:textColor="#FFF"
android:gravity="center_horizontal"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Large Text"
android:id="#+id/bottomText"
android:layout_alignParentBottom="true"
android:layout_alignLeft="#+id/topText"
android:layout_alignStart="#+id/topText"
android:layout_marginBottom="35dp"
android:textColor="#FFF"
android:gravity="center_horizontal" />
</RelativeLayout>
This is set up so you have one activity displaying two fragments. You can see both fragments are included in the activities layout file.
The top fragment needs to communicate with the bottom one to update its text and does so through an interface called TopSelectionListener. You will notice that your activity implements that interface. The other important part is the top fragment keeps a reference to your activity using the interface. You can see that in the top fragment's onAttach method. The activity displaying this fragment must implement the TopSelectionListener interface or else you will get a ClassCastException and your application will crash.
activityCommand = (TopSelectionListener) activity;
When the button is clicked in the top fragment it will call activityCommand.createMeme(...) which calls the createMeme method in your activity.
The createMeme method then looks up a reference to your bottom Fragment and calls the setText method on it to update the text it shows.
There is another example how this works in the Android documentation.

ListView Inside Layout

I need some help creating a listview inside a layout i have. im having torubles creating it properly.
Here is what i got so far.
item.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" >
<LinearLayout
android:id="#+id/listview"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/list_selector" >
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/gradient_bg"
android:src="#drawable/gs3ultimate" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:id="#+id/label"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/thelistarray"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#555555" />
<TextView
android:id="#+id/summary"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/thelistarry_details"
android:textColor="#555555"
android:textSize="10dp" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
Now its just a image on the left, then 2 textview, Now i believe im gonna need 2 string arrys, one for the titles and the 2nd for the details. and i think a 3rd one for the images. Is that right?
Here some java for my list view
AndroidListViewActivity.java
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
public class AndroidListViewActivity extends ListActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// storing string resources into Array
String[] list_array = getResources().getStringArray(R.array.list_array);
// Binding resources Array to ListAdapter
this.setListAdapter(new ArrayAdapter<String>(this, R.layout.item, R.id.label, list_array));
ListView lv = getListView();
// listening to single list item on click
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
}
});
}
}
I know that my java is missing adding the details list_array_details. and i dont know how to add it so it populates. Im not yet using the onitemclick yet for my intent's. However would i determine which one is click and what activity to launch? example. i click list item b and want to like activity "b" but when i click a it launches activity "a"
Any help would be greately appreciated, Thanks in advance.
You need to have a custom adapter for this purpose to populate someother view other than a textview or multiple textviews.
Take a look on customadapter here and here

Android - onTouchListener ClassCastException

I would like to use viewSwitcher to switch between two layouts. It works with a button, but I would like to switch with touching the screen. I've found an onTouchListener example and i tried to implemet some kind of similar, but I did not manage to.
In my main.xml i got one Linear Layout which contains a ViewSwitcher and two other LinearLayout. These are the layouts i want to switch.
here it is:
<ViewSwitcher
android:id="#+id/viewSwitcher"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inAnimation="#android:anim/slide_in_left"
android:outAnimation="#android:anim/slide_out_right" >
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/firstlayout"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#drawable/bg"
android:orientation="vertical" >
<ImageView
android:id="#+id/title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:src="#drawable/titlebar" />
<Button
android:id="#+id/somebut"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="30px"
android:background="#drawable/but" />
</LinearLayout>
<LinearLayout
android:id="#+id/secondlayout"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Second layout" >
</TextView>
</LinearLayout>
</ViewSwitcher>
and my code:
import android.app.Activity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.LinearLayout;
import android.widget.ViewSwitcher;
public class SwitcherActivity extends Activity {
private float downXValue;
private View firstView;
private View SecondView;
private ViewSwitcher vs;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
vs = (ViewSwitcher)findViewById(R.id.viewSwitcher);
firstView= findViewById(R.id.firstlayout);
secondView = findViewById(R.id.secondlayout);
LinearLayout first = (LinearLayout) findViewById(R.id.firstlayout);
first.setOnTouchListener((OnTouchListener) this);
}
public boolean onTouch(View arg0, MotionEvent arg1) {
switch (arg1.getAction()){
case MotionEvent.ACTION_DOWN:{
// store the X value when the user's finger was pressed down
downXValue = arg1.getX();
break;
}
case MotionEvent.ACTION_UP:{
// Get the X value when the user released his/her finger
float currentX = arg1.getX();
// going backwards: pushing stuff to the right
if (downXValue < currentX)
{
if (vs.getCurrentView() != myFirstView)vs.showPrevious();
}
// going forwards: pushing stuff to the left
if (downXValue > currentX)
{
if (vs.getCurrentView() != mySecondView)
vs.showNext();
}
break;
}
}
return true;
}
}
My problem is, that i got ClassCastException in the line which contains the following:
first.setOnTouchListener((OnTouchListener) this);
Your activity has to implement OnTouchListener so that "this" can be used as the listener. Right now it's trying to cast an Activity to an OnTouchListener which is what's throwing the ClassCastException.
You also need to override the OnTouchListener methods to customize the way the touches are handled.

Categories

Resources